from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta
import random

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


COMPANIES = [
    {"name": "ASEAN Secretariat", "industry": "other", "city": "Jakarta", "country": "Indonesia", "website": "https://asean.org", "email": "info@asean.org", "phone": "+62-21-7262991"},
    {"name": "World Bank Group", "industry": "finance", "city": "Jakarta", "country": "Indonesia", "website": "https://worldbank.org", "email": "jakarta@worldbank.org", "phone": "+62-21-5299-3000"},
    {"name": "Asian Development Bank", "industry": "finance", "city": "Jakarta", "country": "Indonesia", "website": "https://adb.org", "email": "jakarta@adb.org", "phone": "+62-21-2512721"},
    {"name": "UN Environment Programme", "industry": "other", "city": "Jakarta", "country": "Indonesia", "website": "https://unep.org", "email": "jakarta@unep.org", "phone": "+62-21-3141308"},
    {"name": "International Labour Organization", "industry": "other", "city": "Jakarta", "country": "Indonesia", "website": "https://ilo.org", "email": "jakarta@ilo.org", "phone": "+62-21-3913112"},
    {"name": "RAND Corporation", "industry": "other", "city": "Jakarta", "country": "Indonesia", "website": "https://rand.org", "email": "info@rand.org", "phone": "+62-21-5550100"},
    {"name": "Brookings Institution", "industry": "education", "city": "Jakarta", "country": "Indonesia", "website": "https://brookings.edu", "email": "info@brookings.edu", "phone": "+62-21-5550200"},
    {"name": "Carnegie Endowment", "industry": "other", "city": "Jakarta", "country": "Indonesia", "website": "https://carnegieendowment.org", "email": "info@carnegieendowment.org", "phone": "+62-21-5550300"},
    {"name": "Friedrich Ebert Foundation", "industry": "other", "city": "Jakarta", "country": "Indonesia", "website": "https://fes.de", "email": "jakarta@fes.de", "phone": "+62-21-3909155"},
    {"name": "Konrad Adenauer Foundation", "industry": "other", "city": "Jakarta", "country": "Indonesia", "website": "https://kas.de", "email": "jakarta@kas.de", "phone": "+62-21-3909256"},
]

CONTACTS = [
    # ASEAN Secretariat
    {"name": "Priya Sharma", "position": "Policy Analyst", "email": "priya.sharma@asean.org", "phone": "+62-811-234-001", "tags": ["policy", "asean"], "company_key": "ASEAN Secretariat", "is_favorite": True},
    {"name": "Rizal Mahendra", "position": "Senior Director", "email": "rizal.mahendra@asean.org", "phone": "+62-811-234-002", "tags": ["policy", "leadership"], "company_key": "ASEAN Secretariat"},
    {"name": "Li Wei", "position": "Economic Affairs Officer", "email": "li.wei@asean.org", "phone": "+62-811-234-003", "tags": ["economics", "asean"], "company_key": "ASEAN Secretariat"},
    # World Bank Group
    {"name": "Marcus Lee", "position": "Senior Economist", "email": "marcus.lee@worldbank.org", "phone": "+62-812-345-001", "tags": ["economics", "finance"], "company_key": "World Bank Group", "is_favorite": True},
    {"name": "Amara Diallo", "position": "Infrastructure Specialist", "email": "amara.diallo@worldbank.org", "phone": "+62-812-345-002", "tags": ["infrastructure", "finance"], "company_key": "World Bank Group"},
    {"name": "Sofia Pereira", "position": "Operations Analyst", "email": "sofia.pereira@worldbank.org", "phone": "+62-812-345-003", "tags": ["operations"], "company_key": "World Bank Group"},
    # Asian Development Bank
    {"name": "Daniel Cruz", "position": "Trade Specialist", "email": "daniel.cruz@adb.org", "phone": "+62-813-456-001", "tags": ["trade", "policy"], "company_key": "Asian Development Bank", "is_favorite": True},
    {"name": "Yui Tanaka", "position": "Financial Analyst", "email": "yui.tanaka@adb.org", "phone": "+62-813-456-002", "tags": ["finance"], "company_key": "Asian Development Bank"},
    {"name": "Arjun Patel", "position": "Project Manager", "email": "arjun.patel@adb.org", "phone": "+62-813-456-003", "tags": ["project", "management"], "company_key": "Asian Development Bank"},
    # UN Environment Programme
    {"name": "Sarah Johnson", "position": "Programme Officer", "email": "sarah.johnson@unep.org", "phone": "+62-814-567-001", "tags": ["environment", "policy"], "company_key": "UN Environment Programme", "is_favorite": True},
    {"name": "Kwame Asante", "position": "Climate Specialist", "email": "kwame.asante@unep.org", "phone": "+62-814-567-002", "tags": ["climate", "environment"], "company_key": "UN Environment Programme"},
    {"name": "Elena Vasquez", "position": "Research Coordinator", "email": "elena.vasquez@unep.org", "phone": "+62-814-567-003", "tags": ["research", "environment"], "company_key": "UN Environment Programme"},
    # International Labour Organization
    {"name": "Ingrid Hoffmann", "position": "Labour Advisor", "email": "ingrid.hoffmann@ilo.org", "phone": "+62-815-678-001", "tags": ["labour", "social"], "company_key": "International Labour Organization", "is_favorite": True},
    {"name": "Budi Santoso", "position": "Employment Specialist", "email": "budi.santoso@ilo.org", "phone": "+62-815-678-002", "tags": ["employment", "social"], "company_key": "International Labour Organization"},
    {"name": "Fatima Al-Hassan", "position": "Skills Development Officer", "email": "fatima.alhassan@ilo.org", "phone": "+62-815-678-003", "tags": ["skills", "social"], "company_key": "International Labour Organization"},
    # RAND Corporation
    {"name": "James Whitfield", "position": "Senior Policy Researcher", "email": "james.whitfield@rand.org", "phone": "+62-816-789-001", "tags": ["research", "policy"], "company_key": "RAND Corporation"},
    {"name": "Mei Lin", "position": "Defense Analyst", "email": "mei.lin@rand.org", "phone": "+62-816-789-002", "tags": ["defense", "security"], "company_key": "RAND Corporation"},
    {"name": "Takashi Yamamoto", "position": "Technology Policy Analyst", "email": "takashi.yamamoto@rand.org", "phone": "+62-816-789-003", "tags": ["technology", "policy"], "company_key": "RAND Corporation"},
    # Brookings Institution
    {"name": "Claire Dubois", "position": "Fellow", "email": "claire.dubois@brookings.edu", "phone": "+62-817-890-001", "tags": ["research", "governance"], "company_key": "Brookings Institution"},
    {"name": "Ahmad Fauzi", "position": "Visiting Scholar", "email": "ahmad.fauzi@brookings.edu", "phone": "+62-817-890-002", "tags": ["research", "economics"], "company_key": "Brookings Institution"},
    {"name": "Nadia Okonkwo", "position": "Research Associate", "email": "nadia.okonkwo@brookings.edu", "phone": "+62-817-890-003", "tags": ["research", "social"], "company_key": "Brookings Institution"},
    # Carnegie Endowment
    {"name": "Robert Chen", "position": "Senior Associate", "email": "robert.chen@carnegieendowment.org", "phone": "+62-818-901-001", "tags": ["geopolitics", "policy"], "company_key": "Carnegie Endowment"},
    {"name": "Irina Petrov", "position": "Associate", "email": "irina.petrov@carnegieendowment.org", "phone": "+62-818-901-002", "tags": ["policy", "security"], "company_key": "Carnegie Endowment"},
    {"name": "Siti Rahmi", "position": "Program Assistant", "email": "siti.rahmi@carnegieendowment.org", "phone": "+62-818-901-003", "tags": ["policy", "asean"], "company_key": "Carnegie Endowment"},
    # Friedrich Ebert Foundation
    {"name": "Hans Müller", "position": "Country Director", "email": "hans.mueller@fes.de", "phone": "+62-819-012-001", "tags": ["governance", "democracy"], "company_key": "Friedrich Ebert Foundation"},
    {"name": "Dewi Kurniawati", "position": "Programme Manager", "email": "dewi.kurniawati@fes.de", "phone": "+62-819-012-002", "tags": ["governance", "social"], "company_key": "Friedrich Ebert Foundation"},
    {"name": "Lars Eriksson", "position": "Project Officer", "email": "lars.eriksson@fes.de", "phone": "+62-819-012-003", "tags": ["democracy", "policy"], "company_key": "Friedrich Ebert Foundation"},
    # Konrad Adenauer Foundation
    {"name": "Katharina Braun", "position": "Resident Representative", "email": "katharina.braun@kas.de", "phone": "+62-820-123-001", "tags": ["governance", "democracy"], "company_key": "Konrad Adenauer Foundation"},
    {"name": "Hendra Wijaya", "position": "Programme Officer", "email": "hendra.wijaya@kas.de", "phone": "+62-820-123-002", "tags": ["policy", "governance"], "company_key": "Konrad Adenauer Foundation"},
    {"name": "Monika Weber", "position": "Project Coordinator", "email": "monika.weber@kas.de", "phone": "+62-820-123-003", "tags": ["democracy", "civil society"], "company_key": "Konrad Adenauer Foundation"},
]

REMINDER_NOTES = [
    "Follow up on policy proposal",
    "Send project brief",
    "Schedule quarterly meeting",
    "Share research report",
    "Confirm event attendance",
    "Review MOU draft",
]


class Command(BaseCommand):
    help = "Seed contacts and companies with linked data"

    def handle(self, *args, **options):
        self.stdout.write("Seeding companies...")
        company_map = {}
        for data in COMPANIES:
            company, created = Company.objects.get_or_create(
                name=data["name"],
                defaults=data,
            )
            company_map[data["name"]] = company
            if created:
                self.stdout.write(f"  Created company: {company.name}")

        self.stdout.write("Seeding contacts...")
        contact_list = []
        for data in CONTACTS:
            company_key = data.pop("company_key")
            data["company"] = company_map[company_key]
            data.setdefault("is_favorite", False)
            contact, created = Contact.objects.get_or_create(
                email=data["email"],
                defaults=data,
            )
            contact_list.append(contact)
            if created:
                self.stdout.write(f"  Created contact: {contact.name}")

        self.stdout.write("Seeding reminders...")
        now = timezone.now()
        for i, contact in enumerate(contact_list[:10]):
            note = REMINDER_NOTES[i % len(REMINDER_NOTES)]
            remind_at = now + timedelta(days=random.randint(1, 14))
            Reminder.objects.get_or_create(
                contact=contact,
                note=note,
                defaults={"remind_at": remind_at},
            )

        self.stdout.write(self.style.SUCCESS(
            f"Done. {Company.objects.count()} companies, "
            f"{Contact.objects.count()} contacts, "
            f"{Reminder.objects.count()} reminders."
        ))
