import json
import os
from django.db.models.signals import post_migrate
from django.dispatch import receiver
from Common.models import Domain, Category, PaymentModeType, PaymentPlanType, Cycle, Level
from School.models import Competency

@receiver(post_migrate)
def common_post_migrate(sender, **kwargs):
    if sender.name != "School":
        return

    # Chemin absolu vers le répertoire Back-End
    backend_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    # Chemins vers les fichiers JSON
    json_files = [
        ("Cycle1.json", 1),
        ("Cycle2.json", 2),
        ("Cycle3.json", 3),
        ("Cycle4.json", 4),
    ]

    for file_name, cycle in json_files:
        json_file_path = os.path.join(backend_dir, "competences", file_name)

        if not os.path.exists(json_file_path):
            print(f"Fichier JSON introuvable : {json_file_path}")
            continue

        with open(json_file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)

        for domain_data in data['domaines']:
            # Vérifiez si le domaine existe déjà
            domain, _ = Domain.objects.get_or_create(name=domain_data['nom'], cycle=cycle)

            for category_data in domain_data['categories']:
                # Vérifiez si la catégorie existe déjà
                category, _ = Category.objects.get_or_create(name=category_data['nom'], domain=domain)

                for competency_data in category_data['competences']:
                    # Vérifiez si la compétence existe déjà
                    competency, _ = Competency.objects.get_or_create(
                        name=competency_data['nom'],
                        end_of_cycle=competency_data.get('fin_cycle', False),
                        level=competency_data.get('niveau'),
                        category=category
                    )
        print(f"Données importées depuis : {json_file_path}")
    
    payment_mode_types = [
        {"code": "SEPA", "label": "Prélèvement SEPA"},
        {"code": "TRANSFER", "label": "Virement"},
        {"code": "CHECK", "label": "Chèque"},
        {"code": "CASH", "label": "Espèce"},
    ]
    for mode in payment_mode_types:
        PaymentModeType.objects.get_or_create(code=mode["code"], defaults={"label": mode["label"]})

    payment_plan_types = [
        {"code": "ONE_TIME", "label": "1 fois"},
        {"code": "THREE_TIMES", "label": "3 fois"},
        {"code": "TEN_TIMES", "label": "10 fois"},
        {"code": "TWELVE_TIMES", "label": "12 fois"},
    ]
    for plan in payment_plan_types:
        PaymentPlanType.objects.get_or_create(code=plan["code"], defaults={"label": plan["label"]})
    
    # Création des cycles
    cycles_data = [
        {"number": 1, "label": "Cycle 1"},
        {"number": 2, "label": "Cycle 2"},
        {"number": 3, "label": "Cycle 3"},
        {"number": 4, "label": "Cycle 4"},
    ]
    cycle_objs = {}
    for cycle in cycles_data:
        obj, _ = Cycle.objects.get_or_create(number=cycle["number"], defaults={"label": cycle["label"]})
        cycle_objs[cycle["number"]] = obj

    # Création des niveaux et association au cycle
    levels_data = [
        {"name": "TPS", "cycle": 1},
        {"name": "PS", "cycle": 1},
        {"name": "MS", "cycle": 1},
        {"name": "GS", "cycle": 1},
        {"name": "CP", "cycle": 2},
        {"name": "CE1", "cycle": 2},
        {"name": "CE2", "cycle": 2},
        {"name": "CM1", "cycle": 3},
        {"name": "CM2", "cycle": 3},
    ]
    for level in levels_data:
        Level.objects.get_or_create(
            name=level["name"],
            defaults={"cycle": cycle_objs[level["cycle"]]}
        )