"""Seed N dummy Candidates for load/UX testing.

Usage (from backend/):
    ./venv/bin/python master_seeder/seed_dummy_candidates.py            # 5000
    ./venv/bin/python master_seeder/seed_dummy_candidates.py 1000       # custom count
    ./venv/bin/python master_seeder/seed_dummy_candidates.py 5000 --reset   # wipe dummies first

Dummies are identified by their email domain `@seed.dummy` (hidden marker) so
they can be removed cleanly without touching real candidates. Uses bulk_create
(skips signals/validators) — fast, and won't create résumé-attachment rows.
"""
import os
import random
import sys

import django

DUMMY_DOMAIN = "seed.dummy"

FIRST = ["Aarav", "Vivaan", "Aditya", "Vihaan", "Arjun", "Sai", "Reyansh", "Krishna", "Ishaan",
         "Rohan", "Ananya", "Diya", "Aadhya", "Saanvi", "Pari", "Anika", "Navya", "Riya", "Myra",
         "Kabir", "Dev", "Aryan", "Kunal", "Nikhil", "Rahul", "Priya", "Neha", "Pooja", "Sneha", "Kavya"]
LAST = ["Sharma", "Verma", "Patel", "Gupta", "Singh", "Kumar", "Reddy", "Nair", "Iyer", "Das",
        "Bose", "Mehta", "Shah", "Joshi", "Rao", "Naidu", "Chopra", "Malhotra", "Kapoor", "Bhat"]
CITIES = ["Pune", "Bengaluru", "Hyderabad", "Mumbai", "Delhi", "Chennai", "Kolkata", "Ahmedabad",
          "Noida", "Gurugram", "Jaipur", "Indore"]
STATES = ["Maharashtra", "Karnataka", "Telangana", "Delhi", "Tamil Nadu", "West Bengal", "Gujarat", "Rajasthan"]
ROLES = ["Software Engineer", "Backend Developer", "Frontend Developer", "Full Stack Developer",
         "DevOps Engineer", "Data Analyst", "QA Engineer", "Business Analyst", "Project Manager",
         "UI/UX Designer", "Android Developer", "ML Engineer", "Support Engineer", "DBA"]
COMPANIES = ["Infosys", "TCS", "Wipro", "Accenture", "Cognizant", "Tech Mahindra", "HCL", "Capgemini",
             "IBM", "Deloitte", "Persistent", "Mindtree", "LTI", "Zensar"]
QUALS = ["B.Tech (CS)", "B.E. (IT)", "MCA", "B.Sc IT", "M.Tech", "BCA", "MBA"]


def run(count: int, reset: bool = False):
    from apps.candidates.models import Candidate
    from django.contrib.auth import get_user_model

    if reset:
        deleted = Candidate.objects.all_with_deleted().filter(email__endswith=f"@{DUMMY_DOMAIN}").delete()
        print(f"RESET: removed existing dummy candidates -> {deleted}")

    from apps.candidates.models import Skill
    from apps.master_data.models import NoticePeriod

    User = get_user_model()
    admin = (User.objects.filter(email="ats@admin.com").first()
             or User.objects.filter(is_superuser=True).first()
             or User.objects.first())

    # Master data to map onto candidates (key skills + notice period).
    skill_ids = list(Skill.objects.values_list("id", flat=True))
    np_pairs = list(NoticePeriod.objects.filter(is_active=True).values_list("value", "id"))
    np_values = [v for v, _ in np_pairs] or [0, 15, 30, 60, 90]
    np_map = {v: pk for v, pk in np_pairs}

    # Unique-ish starting index so re-runs don't clash on email.
    existing = Candidate.objects.all_with_deleted().filter(email__endswith=f"@{DUMMY_DOMAIN}").count()

    rows = []
    for i in range(existing + 1, existing + count + 1):
        fn = random.choice(FIRST)
        ln = random.choice(LAST)
        fresher = random.random() < 0.25
        exp = 0 if fresher else round(random.uniform(1, 15), 1)
        np_val = random.choice(np_values)
        cur_ctc = None if fresher else round(random.uniform(4, 30), 2)      # Current Pay (LPA)
        exp_ctc = round((cur_ctc or random.uniform(3, 6)) + random.uniform(1, 8), 2)  # Desired Pay (LPA)
        rows.append(Candidate(
            first_name=fn,
            last_name=ln,
            email=f"{fn.lower()}.{ln.lower()}.{i}@{DUMMY_DOMAIN}",
            phone_number=f"9{random.randint(100000000, 999999999)}",
            city=random.choice(CITIES),
            state=random.choice(STATES),
            country="India",
            fresher=fresher,
            total_experience=exp,
            current_company=("" if fresher else random.choice(COMPANIES)),
            current_role=("" if fresher else random.choice(ROLES)),
            current_location=random.choice(CITIES),
            current_ctc=cur_ctc,                    # Current Pay
            expected_ctc=exp_ctc,                   # Desired Pay
            notice_period=np_val,                   # Notice Period (days)
            notice_period_ref_id=np_map.get(np_val),  # mapped to NoticePeriod master
            highest_qualification=random.choice(QUALS),
            university=random.choice(["Pune University", "VTU", "Anna University", "Delhi University", "IIT", "NIT"]),
            passing_year=random.randint(2008, 2024),
            status=random.choice(["Profile Completed", "Verified", "Draft"]),
            source="OTHER",
            created_by=admin,
        ))

    created = 0
    Through = Candidate.skills.through   # M2M join table (bulk_create doesn't set M2M)
    for start in range(0, len(rows), 1000):
        chunk = rows[start:start + 1000]
        Candidate.objects.bulk_create(chunk)
        # Map 3-6 key skills onto each candidate via the join table.
        if skill_ids:
            links = []
            for c in chunk:
                for sid in random.sample(skill_ids, min(len(skill_ids), random.randint(3, 6))):
                    links.append(Through(candidate_id=c.id, skill_id=sid))
            Through.objects.bulk_create(links, ignore_conflicts=True)
        created += len(chunk)
        print(f"  inserted {created}/{len(rows)}")
    print(f"Done. Seeded {created} dummy candidates.")
    print(f"Remove later: Candidate.objects.all_with_deleted().filter(email__endswith='@{DUMMY_DOMAIN}').delete()")


if __name__ == "__main__":
    sys.path.append(os.path.dirname(os.path.dirname(__file__)))
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")
    django.setup()
    args = sys.argv[1:]
    n = 5000
    for a in args:
        if a.isdigit():
            n = int(a)
    run(n, reset="--reset" in args)
