"""Seed N dummy Job Descriptions for load/UX testing.

Usage (from backend/):
    ./venv/bin/python master_seeder/seed_dummy_jds.py            # 1000 JDs
    ./venv/bin/python master_seeder/seed_dummy_jds.py 250        # custom count
    ./venv/bin/python master_seeder/seed_dummy_jds.py 1000 --published-only

Idempotent-ish: titles are suffixed with a unique index + a batch tag so re-runs
add fresh rows rather than clashing. created_by = an admin user; client = a random
existing client (or none). Uses bulk_create for speed.
"""
import os
import random
import sys

import django

BATCH_TAG = "DUMMY"

ROLES = [
    "Software Engineer", "Senior Backend Developer", "Frontend Developer", "Full Stack Developer",
    "DevOps Engineer", "Data Analyst", "Data Scientist", "QA Engineer", "Automation Tester",
    "Product Manager", "Project Manager", "Business Analyst", "UI/UX Designer", "SOC Analyst",
    "Network Engineer", "Cloud Architect", "Android Developer", "iOS Developer", "ML Engineer",
    "Technical Support Engineer", "Database Administrator", "Scrum Master", "Solutions Architect",
]
CITIES = ["Pune", "Bengaluru", "Hyderabad", "Mumbai", "Delhi NCR", "Chennai", "Kolkata",
          "Ahmedabad", "Noida", "Gurugram", "Remote", "Port Blair"]
EXP = ["0-1 years", "1-3 years", "3-5 years", "5-8 years", "8-12 years"]
CTC = ["3-5 LPA", "5-9 LPA", "9-14 LPA", "12-18 LPA", "18-28 LPA", "25-40 LPA"]
NOTICE = ["Immediate", "15 days", "30 days", "60 days", "90 days"]
SHIFTS = ["Day", "Night", "Rotational", "Flexible"]
WORKING = ["5 days (Mon-Fri)", "6 days (Mon-Sat)", "5 days (rotational roster)"]
SKILLS = ["Python", "Django", "React", "Next.js", "Node.js", "PostgreSQL", "AWS", "Docker",
          "Kubernetes", "TypeScript", "Java", "Spring Boot", "SQL", "REST API", "Git", "CI/CD",
          "Linux", "Redis", "GraphQL", "Selenium", "Splunk", "Terraform"]
QUALS = ["B.Tech/B.E. (CS/IT)", "B.Sc IT / BCA", "MCA / M.Tech", "Any graduate", "B.Tech + relevant certs"]
PRIORITY = ["High", "Medium", "Low"]


def run(count: int, published_only: bool, reset: bool = False):
    from apps.jobs.models import JobDescription
    from apps.clients.models import Client
    from django.contrib.auth import get_user_model

    if reset:
        # Destructive: removes ALL JDs (and cascades pipeline/postings/approvals).
        deleted = JobDescription.objects.all().delete()
        print(f"RESET: deleted all existing JDs -> {deleted}")
        # Reset the auto-increment sequence so new ids start at 1 again.
        from django.db import connection
        with connection.cursor() as cur:
            cur.execute("ALTER SEQUENCE job_descriptions_id_seq RESTART WITH 1;")
        print("RESET: job_descriptions id sequence restarted at 1")

    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())
    if not admin:
        print("No user found — run the user seeder first.")
        return

    client_ids = list(Client.objects.values_list("id", flat=True)) or [None]

    rows = []
    for i in range(1, count + 1):
        role = random.choice(ROLES)
        must = ", ".join(random.sample(SKILLS, random.randint(3, 6)))
        good = ", ".join(random.sample(SKILLS, random.randint(2, 4)))
        if published_only:
            status = "Published"
        else:
            status = random.choices(["Published", "Draft", "Closed"], weights=[70, 25, 5])[0]
        approval = "APPROVED" if status == "Published" else ("CLOSED" if status == "Closed" else "DRAFT")
        rows.append(JobDescription(
            title=role,
            # Hidden marker (not shown in UI) so dummies can be removed cleanly.
            rank_weights={"seed_dummy": True},
            department=random.choice(["Engineering", "Security Operations", "Data", "Product", "QA", "IT"]),
            location=random.choice(CITIES),
            experience_band=random.choice(EXP),
            ctc_band=random.choice(CTC),
            notice_period=random.choice(NOTICE),
            shift=random.choice(SHIFTS),
            must_have_skills=must,
            good_to_have_skills=good,
            qualifications=random.choice(QUALS),
            working_days=random.choice(WORKING),
            num_positions=random.randint(1, 8),
            work_details=(f"We are hiring a {role}. Responsibilities include building and maintaining "
                          f"production systems, collaborating with cross-functional teams, and owning "
                          f"delivery end to end. Skills: {must}."),
            status=status,
            approval_status=approval,
            priority=random.choice(PRIORITY),
            created_by=admin,
            client_id=random.choice(client_ids),
        ))

    created = 0
    for start in range(0, len(rows), 500):
        chunk = rows[start:start + 500]
        JobDescription.objects.bulk_create(chunk)
        created += len(chunk)
        print(f"  inserted {created}/{len(rows)}")
    print(f"Done. Seeded {created} dummy JDs (created_by={admin.email}).")
    print("To remove later: JobDescription.objects.filter(rank_weights__seed_dummy=True).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 = [a for a in sys.argv[1:]]
    n = 1000
    for a in args:
        if a.isdigit():
            n = int(a)
    run(n, "--published-only" in args, reset="--reset" in args)
