import os
import django
import random
from datetime import date, timedelta
from decimal import Decimal

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "facturation.settings")
django.setup()

from billing.models import (
    Client, TypeService, Service, FraisStandard, Dossier, 
    LigneDossier, Proforma, Facture, Societe
)
from dgi.models import TaxGroup, ItemType, ClientType

def run():
    print("Creation des données de test (Fake Data)...")

    # 1. DGI Reference Data
    # Tax Groups
    tg_a, _ = TaxGroup.objects.get_or_create(
        code="A", defaults={"name": "TVA 16%", "tax": 16.00}
    )
    tg_b, _ = TaxGroup.objects.get_or_create(
        code="B", defaults={"name": "TVA 16% (Sauf)", "tax": 16.00}
    )
    tg_e, _ = TaxGroup.objects.get_or_create(
        code="E", defaults={"name": "Exonéré", "tax": 0.00}
    )

    # Item Types
    it_srv, _ = ItemType.objects.update_or_create(
        code="SER", defaults={"name": "Services"}
    )
    it_gds, _ = ItemType.objects.update_or_create(
        code="BIE", defaults={"name": "Biens"}
    )
    
    # Client Types
    ct_pm, _ = ClientType.objects.update_or_create(
        code="PM", defaults={"name": "Personne Morale"}
    )
    ct_pp, _ = ClientType.objects.update_or_create(
        code="PP", defaults={"name": "Personne Physique"}
    )

    # 2. Type Services (Billing)
    ts_frais, _ = TypeService.objects.get_or_create(
        code="FRAIS", defaults={"designation": "Honoraires & Services Socodam"}
    )
    ts_debours, _ = TypeService.objects.get_or_create(
        code="DEBOURS", defaults={"designation": "Débours & Taxes"}
    )

    # 3. Services (Catalogue)
    services_data = [
        ("DOC", "Frais de Documentation", ts_frais, tg_a),
        ("MAN", "Manutention & Logistique", ts_frais, tg_a),
        ("TRP", "Transport Local / Livraison", ts_frais, tg_a),
        ("HON", "Honoraires de Transit", ts_frais, tg_a),
        ("MAG", "Frais de Magasinage", ts_debours, tg_a), # Souvent taxable
        ("DOU", "Droits et Taxes Douane", ts_debours, tg_e), # Non taxable (Tiers)
        ("OCC", "Frais OCC / BIVAC", ts_debours, tg_e),
        ("FPI", "Taxe FPI", ts_debours, tg_e),
    ]

    for code, nom, ts, tg in services_data:
        Service.objects.update_or_create(
            code=code,
            defaults={
                "designation": nom,
                "type_service": ts,
                "taxgroup": tg,
                "typeart": it_srv,
                "actif": True
            }
        )
    print(f"{len(services_data)} Services vérifiés/créés.")

    # 4. Clients
    clients_data = [
        ("KIBALI GOLD MINES", "Haut-Uele, Province Orientale, RDC", "A0111111A"),
        ("BRACONGO SA", "Av. des Poids Lourds, Kinshasa/Limete", "A0222222B"),
        ("TENKE FUNGURUME MINING", "Route Kolwezi, Lualaba, RDC", "A0333333C"),
        ("UNICEF RDC", "Blvd du 30 Juin, Kinshasa/Gombe", "A0444444D"),
    ]

    clients_objs = []
    for nom, adr, nif in clients_data:
        clt, _ = Client.objects.get_or_create(
            nif=nif,
            defaults={
                "nom": nom,
                "name": nom, # DGI field
                "adresse": adr,
                "address": adr, # DGI field
                "telephone": "+243 00 000 0000",
                "contact": "+243 00 000 0000", # DGI field
                "client_type": ct_pm,
                "solde_compte": 0.00
            }
        )
        clients_objs.append(clt)
    print(f"{len(clients_objs)} Clients vérifiés/créés.")

    # 5. Societe (Configuration)
    soc, _ = Societe.objects.get_or_create(
        nom="Socodam s.a.r.l.",
        defaults={
            "sous_titre": "Agence Internationale de Logistique, Transit et Services",
            "nif": "A1116228C", # DGI field
            "n_impot": "A1116228C",
            "rccm": "CD/KIN/RCCM/14-B-01536",
            "id_nat": "01-718-N63783F",
            "isf_dgi": "ISF-TEST-001",
            "adresse_physique": "Avenue ex Poids Lourds n° 1963 (Concession Sucrière)\nKinshasa : Gombe"
        }
    )
    print("Société configurée.")

    # 6. Dossiers de test
    if len(clients_objs) > 0:
        # Dossier 1: Import Minier (Kibali)
        d1, created1 = Dossier.objects.get_or_create(
            ref_client="KGM-ORD-2024-001",
            defaults={
                "client": clients_objs[0],
                "description": "Pièces de rechange pour engins miniers",
                "vol": "ET-843",
                "mawb": "071-44556677",
                "poids": 2500.00,
                "nombre_colis": 4,
                "statut": "EN_COURS",
                "date_arrivee": date.today() - timedelta(days=5),
                "declaration_dgda": "E-998877",
            }
        )
        if created1:
            # Lignes
            LigneDossier.objects.create(dossier=d1, service=Service.objects.get(code="DOC"), montant=150.00)
            LigneDossier.objects.create(dossier=d1, service=Service.objects.get(code="HON"), montant=2000.00)
            LigneDossier.objects.create(dossier=d1, service=Service.objects.get(code="DOU"), montant=12500.00)
            LigneDossier.objects.create(dossier=d1, service=Service.objects.get(code="TRP"), montant=3500.00)
            print("Dossier KIBALI créé.")

        # Dossier 2: Import Industriel (Bracongo)
        d2, created2 = Dossier.objects.get_or_create(
            ref_client="PO-BRA-099",
            defaults={
                "client": clients_objs[1],
                "description": "Intrants Chimiques (Malt)",
                "vol": "SN-300",
                "mawb": "082-11223344",
                "poids": 15000.00,
                "nombre_colis": 200,
                "statut": "BROUILLON",
                "date_arrivee": date.today() - timedelta(days=2),
            }
        )
        if created2:
             LigneDossier.objects.create(dossier=d2, service=Service.objects.get(code="DOC"), montant=100.00)
             LigneDossier.objects.create(dossier=d2, service=Service.objects.get(code="MAN"), montant=450.00)
             print("Dossier BRACONGO créé.")

    # 7. Proforma (pour test immédiat)
    if Dossier.objects.filter(ref_client="KGM-ORD-2024-001").exists():
        d_kibali = Dossier.objects.get(ref_client="KGM-ORD-2024-001")
        if not Proforma.objects.filter(dossier=d_kibali).exists():
            prof = Proforma.objects.create(dossier=d_kibali, statut='BROUILLON')
            print(f"Proforma créée pour le dossier {d_kibali.numero}")
    
    print("Terminé !")

if __name__ == "__main__":
    run()
