from django.core.management.base import BaseCommand

from apps.contacts.models import Contact
from apps.companies.models import Company


# Map email domain -> canonical company name.
# If the company does not exist yet, it is created with the defaults below.
DOMAIN_MAP = {
    "csis.or.id": {
        "name": "CSIS Indonesia",
        "legal_name": "Centre for Strategic and International Studies",
        "industry": "education",
        "city": "Jakarta",
        "country": "Indonesia",
        "website": "https://www.csis.or.id",
        "email": "csis@csis.or.id",
        "phone": "+62-21-3865532",
        "description": "Indonesian think tank on policy, economics, security.",
    },
    "smeru.or.id": {
        "name": "SMERU Research Institute",
        "industry": "education",
        "city": "Jakarta",
        "country": "Indonesia",
        "website": "https://smeru.or.id",
        "email": "smeru@smeru.or.id",
        "phone": "+62-21-3193-6336",
        "description": "Independent research on poverty and inequality.",
    },
    "theindonesianinstitute.com": {
        "name": "The Indonesian Institute",
        "industry": "education",
        "city": "Jakarta",
        "country": "Indonesia",
        "website": "https://www.theindonesianinstitute.com",
        "email": "contact@theindonesianinstitute.com",
        "phone": "+62-21-7279-5252",
        "description": "Center for public policy research.",
    },
    "ipac.or.id": {
        "name": "Institute for Policy Analysis of Conflict",
        "industry": "other",
        "city": "Jakarta",
        "country": "Indonesia",
        "website": "https://www.understandingconflict.org",
        "email": "info@ipac.or.id",
        "phone": "+62-21-3983-0023",
        "description": "Conflict analysis and policy research.",
    },
    "habibiecenter.or.id": {
        "name": "The Habibie Center",
        "industry": "education",
        "city": "Jakarta",
        "country": "Indonesia",
        "website": "https://habibiecenter.or.id",
        "email": "thc@habibiecenter.or.id",
        "phone": "+62-21-7817211",
        "description": "Democracy, human rights, and policy research.",
    },
    "lipi.go.id": {
        "name": "BRIN (formerly LIPI)",
        "industry": "education",
        "city": "Jakarta",
        "country": "Indonesia",
        "website": "https://www.brin.go.id",
        "email": "humas@brin.go.id",
        "phone": "+62-21-525-1542",
        "description": "National Research and Innovation Agency.",
    },
    "indef.or.id": {
        "name": "INDEF",
        "legal_name": "Institute for Development of Economics and Finance",
        "industry": "education",
        "city": "Jakarta",
        "country": "Indonesia",
        "website": "https://indef.or.id",
        "email": "indef@indef.or.id",
        "phone": "+62-21-7919-8112",
        "description": "Economics and finance research institute.",
    },
    "cips-indonesia.org": {
        "name": "Center for Indonesian Policy Studies",
        "industry": "education",
        "city": "Jakarta",
        "country": "Indonesia",
        "website": "https://www.cips-indonesia.org",
        "email": "contact@cips-indonesia.org",
        "phone": "+62-21-7211-1180",
        "description": "Independent public policy think tank.",
    },
}


class Command(BaseCommand):
    help = "Link existing contacts to organizations by email domain. Creates orgs if missing."

    def add_arguments(self, parser):
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        dry = options.get("dry_run", False)

        if dry:
            self.stdout.write(self.style.WARNING("Dry run — no DB writes."))

        # Ensure orgs exist
        org_map = {}
        for domain, defaults in DOMAIN_MAP.items():
            if dry:
                exists = Company.objects.filter(name=defaults["name"]).exists()
                self.stdout.write(f"  [{'skip' if exists else 'create'}] org {defaults['name']} ({domain})")
                continue
            company, created = Company.objects.get_or_create(
                name=defaults["name"],
                defaults=defaults,
            )
            org_map[domain] = company
            if created:
                self.stdout.write(f"  + org {company.name}")

        # Link contacts
        unlinked = Contact.objects.filter(company__isnull=True)
        linked = 0
        skipped = 0
        for c in unlinked:
            email = (c.email or "").strip().lower()
            if "@" not in email:
                skipped += 1
                continue
            domain = email.rsplit("@", 1)[-1]
            if domain not in DOMAIN_MAP:
                skipped += 1
                continue

            target_name = DOMAIN_MAP[domain]["name"]
            if dry:
                self.stdout.write(f"  [link] {c.name} <{c.email}> -> {target_name}")
                linked += 1
                continue

            company = org_map.get(domain) or Company.objects.filter(name=target_name).first()
            if company is None:
                skipped += 1
                continue
            c.company = company
            c.save(update_fields=["company"])
            linked += 1
            self.stdout.write(f"  ~ linked {c.name} -> {company.name}")

        if dry:
            self.stdout.write(self.style.SUCCESS(f"Dry run done. linked={linked} skipped={skipped}"))
            return

        self.stdout.write(self.style.SUCCESS(
            f"Done. linked {linked}, left unlinked {skipped}."
        ))
