import django
import os
import sys


CLIENTS = [
    {
        "name": "TechNova Solutions Pvt Ltd",
        "email": "hr@technovasolutions.in",
        "phone": "+91 98100 23451",
        "website": "https://www.technovasolutions.in",
        "description": "Mid-size IT services firm specializing in cloud migration and enterprise app modernization for BFSI clients.",
    },
    {
        "name": "FinEdge Capital Services",
        "email": "careers@finedgecapital.com",
        "phone": "+91 99870 45612",
        "website": "https://www.finedgecapital.com",
        "description": "NBFC offering digital lending and wealth management products across tier-1 and tier-2 cities.",
    },
    {
        "name": "MediCore Health Systems",
        "email": "talent@medicorehealth.in",
        "phone": "+91 98765 33210",
        "website": "https://www.medicorehealth.in",
        "description": "Healthcare technology company building hospital management and telemedicine platforms.",
    },
    {
        "name": "GreenGrid Energy Ltd",
        "email": "recruitment@greengridenergy.com",
        "phone": "+91 97112 88904",
        "website": "https://www.greengridenergy.com",
        "description": "Renewable energy company managing solar and wind assets with a growing IoT-based monitoring division.",
    },
    {
        "name": "ShopSphere Retail Tech",
        "email": "jobs@shopsphere.io",
        "phone": "+91 96543 21087",
        "website": "https://www.shopsphere.io",
        "description": "E-commerce enablement startup providing omnichannel POS and inventory solutions to D2C brands.",
    },
    {
        "name": "Quantum Logistics India",
        "email": "hiring@quantumlogistics.in",
        "phone": "+91 98221 67453",
        "website": "https://www.quantumlogistics.in",
        "description": "Supply chain and last-mile delivery company operating in 120+ cities with a tech-first fleet platform.",
    },
    {
        "name": "EduBridge Learning Pvt Ltd",
        "email": "hr@edubridgelearning.com",
        "phone": "+91 99001 54327",
        "website": "https://www.edubridgelearning.com",
        "description": "EdTech company delivering upskilling programs in partnership with universities and corporates.",
    },
    {
        "name": "SecureStack Cyber Solutions",
        "email": "talent@securestack.co.in",
        "phone": "+91 98330 76521",
        "website": "https://www.securestack.co.in",
        "description": "Cybersecurity consulting firm offering SOC services, VAPT, and compliance audits for enterprises.",
    },
    {
        "name": "AeroWorks Engineering",
        "email": "careers@aeroworkseng.com",
        "phone": "+91 97890 12345",
        "website": "https://www.aeroworkseng.com",
        "description": "Precision engineering and aerospace components manufacturer with plants in Pune and Bengaluru.",
    },
    {
        "name": "BlueOrbit Media Group",
        "email": "people@blueorbitmedia.in",
        "phone": "+91 98450 67890",
        "website": "https://www.blueorbitmedia.in",
        "description": "Digital media and ad-tech agency handling performance marketing for consumer brands.",
    },
]

JDS = [
    {
        "title": "Senior Java Backend Developer",
        "client": "TechNova Solutions Pvt Ltd",
        "department": "Engineering",
        "location": "Noida",
        "experience_band": "5-8 years",
        "ctc_band": "18-24 LPA",
        "notice_period": "30 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 3,
        "status": "Published",
        "priority": "High",
        "must_have_skills": "Java 17, Spring Boot, Microservices, REST APIs, PostgreSQL, Kafka",
        "good_to_have_skills": "AWS, Docker, Kubernetes, Redis",
        "qualifications": "B.Tech/B.E. in CS/IT or MCA",
        "certification": "Oracle Certified Professional Java SE (preferred)",
        "questions": [
            "Describe a microservice you designed end-to-end.",
            "How do you handle distributed transactions?",
            "What is your current and expected CTC?",
        ],
        "work_details": "Design and build scalable backend services for a BFSI cloud-migration program; own API design, code reviews, and production support for assigned modules.",
    },
    {
        "title": "DevOps Engineer",
        "client": "TechNova Solutions Pvt Ltd",
        "department": "Engineering",
        "location": "Noida / Remote",
        "experience_band": "3-5 years",
        "ctc_band": "12-18 LPA",
        "notice_period": "30 days",
        "shift": "Flexible",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 2,
        "status": "Published",
        "priority": "High",
        "must_have_skills": "AWS, Terraform, Jenkins/GitHub Actions, Docker, Kubernetes, Linux",
        "good_to_have_skills": "Prometheus, Grafana, Python scripting, Ansible",
        "qualifications": "B.Tech/B.E. in any engineering stream",
        "certification": "AWS Certified Solutions Architect - Associate",
        "questions": [
            "Walk me through a CI/CD pipeline you built.",
            "How do you manage secrets in Kubernetes?",
        ],
        "work_details": "Own CI/CD pipelines and IaC for client environments; drive infra cost optimization and on-call incident response on a weekly rotation.",
    },
    {
        "title": "Credit Risk Analyst",
        "client": "FinEdge Capital Services",
        "department": "Risk & Compliance",
        "location": "Mumbai",
        "experience_band": "2-4 years",
        "ctc_band": "8-12 LPA",
        "notice_period": "60 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 2,
        "status": "Published",
        "priority": "Medium",
        "must_have_skills": "Credit underwriting, financial statement analysis, Excel, SQL",
        "good_to_have_skills": "Python (pandas), Power BI, exposure to digital lending models",
        "qualifications": "MBA (Finance) or CA Inter / CFA L1",
        "certification": "",
        "questions": [
            "How would you assess creditworthiness of a thin-file customer?",
            "Which risk metrics do you track monthly?",
        ],
        "work_details": "Build and monitor credit scorecards for the digital lending portfolio; publish monthly portfolio risk reviews and support policy revisions.",
    },
    {
        "title": "Full Stack Developer (React + Node)",
        "client": "FinEdge Capital Services",
        "department": "Technology",
        "location": "Mumbai",
        "experience_band": "3-6 years",
        "ctc_band": "14-20 LPA",
        "notice_period": "30 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 4,
        "status": "Published",
        "priority": "High",
        "must_have_skills": "React, Node.js, TypeScript, MongoDB/PostgreSQL, REST",
        "good_to_have_skills": "Next.js, GraphQL, AWS Lambda, Jest",
        "qualifications": "B.Tech/B.E./MCA",
        "certification": "",
        "questions": [
            "Explain how you'd secure a customer-facing lending app.",
            "Preferred state-management approach and why?",
        ],
        "work_details": "Develop customer onboarding and loan-servicing journeys for web; work in a 2-week sprint model with product and design.",
    },
    {
        "title": "Clinical Data Analyst",
        "client": "MediCore Health Systems",
        "department": "Data & Analytics",
        "location": "Hyderabad",
        "experience_band": "2-5 years",
        "ctc_band": "7-11 LPA",
        "notice_period": "30 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 2,
        "status": "Draft",
        "priority": "Medium",
        "must_have_skills": "SQL, Excel, healthcare data (HL7/FHIR exposure), reporting dashboards",
        "good_to_have_skills": "Python, Tableau, knowledge of NABH/HIPAA compliance",
        "qualifications": "B.Sc/M.Sc in Life Sciences, B.Pharm, or B.Tech Biomedical",
        "certification": "",
        "questions": [
            "What experience do you have with EMR/EHR datasets?",
        ],
        "work_details": "Analyze hospital operational and clinical datasets to build quality-of-care dashboards for hospital administrators.",
    },
    {
        "title": "Flutter Mobile Developer",
        "client": "MediCore Health Systems",
        "department": "Engineering",
        "location": "Hyderabad",
        "experience_band": "3-5 years",
        "ctc_band": "10-15 LPA",
        "notice_period": "Immediate",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 1,
        "status": "Published",
        "priority": "High",
        "must_have_skills": "Flutter, Dart, REST integration, state management (Bloc/Riverpod), Firebase",
        "good_to_have_skills": "Native Android/iOS basics, CI for mobile, video-call SDK integration",
        "qualifications": "B.Tech/B.E./MCA",
        "certification": "",
        "questions": [
            "Have you published apps to both stores? Share links.",
            "How do you handle offline-first sync?",
        ],
        "work_details": "Own the patient-facing telemedicine app end-to-end - appointment booking, video consult, and e-prescription modules.",
    },
    {
        "title": "IoT Firmware Engineer",
        "client": "GreenGrid Energy Ltd",
        "department": "R&D",
        "location": "Chennai",
        "experience_band": "4-7 years",
        "ctc_band": "15-22 LPA",
        "notice_period": "45 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 2,
        "status": "Published",
        "priority": "Medium",
        "must_have_skills": "Embedded C/C++, RTOS, MQTT, Modbus, ESP32/STM32",
        "good_to_have_skills": "LoRaWAN, OTA update pipelines, PCB debugging",
        "qualifications": "B.Tech/M.Tech in Electronics/Embedded Systems",
        "certification": "",
        "questions": [
            "Describe a low-power optimization you implemented.",
            "Experience with solar inverter or energy-meter protocols?",
        ],
        "work_details": "Develop firmware for solar plant monitoring devices; work with the cloud team on telemetry schema and OTA rollout.",
    },
    {
        "title": "Site Operations Manager",
        "client": "GreenGrid Energy Ltd",
        "department": "Operations",
        "location": "Jaisalmer",
        "experience_band": "6-10 years",
        "ctc_band": "12-16 LPA",
        "notice_period": "60 days",
        "shift": "Rotational",
        "working_days": "6 days (Mon-Sat)",
        "num_positions": 1,
        "status": "Draft",
        "priority": "Low",
        "must_have_skills": "Solar/wind plant O&M, team management, HSE compliance, vendor management",
        "good_to_have_skills": "SCADA familiarity, Hindi + Rajasthani fluency",
        "qualifications": "B.Tech Electrical/Mechanical",
        "certification": "NEBOSH IGC (preferred)",
        "questions": [
            "Largest site capacity you have managed?",
            "Willing to relocate to Jaisalmer?",
        ],
        "work_details": "Manage day-to-day operations of a 150 MW solar site including preventive maintenance schedules, contractor teams, and grid compliance reporting.",
    },
    {
        "title": "Product Manager - POS Platform",
        "client": "ShopSphere Retail Tech",
        "department": "Product",
        "location": "Bengaluru",
        "experience_band": "5-8 years",
        "ctc_band": "25-35 LPA",
        "notice_period": "60 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 1,
        "status": "Published",
        "priority": "High",
        "must_have_skills": "5+ years product management, B2B SaaS, roadmap ownership, stakeholder management",
        "good_to_have_skills": "Retail/POS domain, SQL, experimentation frameworks",
        "qualifications": "B.Tech + MBA preferred",
        "certification": "CSPO (preferred)",
        "questions": [
            "Describe a product you took from 0 to 1.",
            "How do you prioritize a conflicting feature backlog?",
        ],
        "work_details": "Own the POS product line roadmap; run discovery with D2C merchants, define quarterly OKRs, and ship with two engineering pods.",
    },
    {
        "title": "QA Automation Engineer",
        "client": "ShopSphere Retail Tech",
        "department": "Quality",
        "location": "Bengaluru",
        "experience_band": "2-4 years",
        "ctc_band": "8-12 LPA",
        "notice_period": "30 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 3,
        "status": "Published",
        "priority": "Medium",
        "must_have_skills": "Selenium/Playwright, Java or Python, API testing (Postman/RestAssured), Git",
        "good_to_have_skills": "Performance testing (JMeter), CI integration, mobile automation (Appium)",
        "qualifications": "B.Tech/B.E./MCA",
        "certification": "ISTQB Foundation (preferred)",
        "questions": [
            "What's your framework design approach for a new project?",
        ],
        "work_details": "Build and maintain the automation suite for web and API layers of the omnichannel platform; target 80% regression coverage.",
    },
    {
        "title": "Fleet Data Scientist",
        "client": "Quantum Logistics India",
        "department": "Analytics",
        "location": "Gurugram",
        "experience_band": "3-6 years",
        "ctc_band": "16-22 LPA",
        "notice_period": "30 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 1,
        "status": "Published",
        "priority": "Medium",
        "must_have_skills": "Python, ML (regression/classification), SQL, geospatial data handling",
        "good_to_have_skills": "Route-optimization algorithms, PySpark, MLOps basics",
        "qualifications": "B.Tech/M.Tech/M.Sc in CS, Statistics, or OR",
        "certification": "",
        "questions": [
            "Explain a model you deployed to production and its business impact.",
        ],
        "work_details": "Build ETA-prediction and route-optimization models for last-mile fleet; partner with ops teams to A/B test dispatch strategies.",
    },
    {
        "title": "Academic Counselor",
        "client": "EduBridge Learning Pvt Ltd",
        "department": "Sales",
        "location": "Delhi NCR",
        "experience_band": "1-3 years",
        "ctc_band": "4-6 LPA",
        "notice_period": "Immediate",
        "shift": "Rotational",
        "working_days": "6 days (Tue-Sun)",
        "num_positions": 5,
        "status": "Published",
        "priority": "High",
        "must_have_skills": "Inside sales / counseling experience, strong Hindi + English communication, CRM usage",
        "good_to_have_skills": "EdTech background, regional language skills",
        "qualifications": "Any graduate",
        "certification": "",
        "questions": [
            "Comfortable with revenue targets?",
            "Comfortable with a Tue-Sun week (Monday off)?",
        ],
        "work_details": "Counsel prospective learners on upskilling programs over calls and walk-ins; own the lead-to-enrollment funnel with monthly targets.",
    },
    {
        "title": "SOC Analyst L2",
        "client": "SecureStack Cyber Solutions",
        "department": "Security Operations",
        "location": "Pune",
        "experience_band": "3-5 years",
        "ctc_band": "9-14 LPA",
        "notice_period": "30 days",
        "shift": "Night",
        "working_days": "5 days (rotational roster)",
        "num_positions": 3,
        "status": "Published",
        "priority": "High",
        "must_have_skills": "SIEM (Splunk/QRadar), incident triage, MITRE ATT&CK, log analysis",
        "good_to_have_skills": "SOAR tools, threat hunting, scripting (Python)",
        "qualifications": "B.Tech/B.E. or B.Sc IT",
        "certification": "CEH or CompTIA Security+",
        "questions": [
            "Walk through your response to a suspected ransomware alert.",
            "Comfortable with night shifts?",
        ],
        "work_details": "Handle L2 escalations in a 24x7 SOC, tune SIEM rules, mentor L1 analysts, and contribute to monthly threat reports for enterprise clients.",
    },
    {
        "title": "CNC Programmer - Aerospace",
        "client": "AeroWorks Engineering",
        "department": "Manufacturing",
        "location": "Pune",
        "experience_band": "4-8 years",
        "ctc_band": "6-10 LPA",
        "notice_period": "30 days",
        "shift": "Rotational",
        "working_days": "6 days (Mon-Sat)",
        "num_positions": 2,
        "status": "Draft",
        "priority": "Medium",
        "must_have_skills": "CNC programming (Fanuc/Siemens), 5-axis machining, GD&T, CAM software (Mastercam/NX)",
        "good_to_have_skills": "Aerospace alloys (titanium/Inconel) experience, AS9100 exposure",
        "qualifications": "Diploma/B.Tech Mechanical or Production",
        "certification": "",
        "questions": [
            "Which 5-axis machines have you programmed?",
            "Experience with first-article inspection?",
        ],
        "work_details": "Program and prove out CNC machining for precision aerospace components; work with quality on FAI documentation under AS9100.",
    },
    {
        "title": "Performance Marketing Lead",
        "client": "BlueOrbit Media Group",
        "department": "Digital Marketing",
        "location": "Bengaluru",
        "experience_band": "4-6 years",
        "ctc_band": "12-18 LPA",
        "notice_period": "45 days",
        "shift": "Day",
        "working_days": "5 days (Mon-Fri)",
        "num_positions": 1,
        "status": "Closed",
        "priority": "Low",
        "must_have_skills": "Google Ads, Meta Ads, budget ownership (50L+/month), GA4, ROAS optimization",
        "good_to_have_skills": "Programmatic (DV360), CRO, marketing automation",
        "qualifications": "Any graduate; MBA Marketing preferred",
        "certification": "Google Ads Certification",
        "questions": [
            "Largest monthly ad budget managed and results achieved?",
        ],
        "work_details": "Lead a 4-member team running performance campaigns for consumer brand clients; own ROAS targets, reporting cadence, and client reviews.",
    },
]


def seed_data(stdout=None):
    from django.utils import timezone
    from apps.clients.models import Client
    from apps.jobs.models import JobDescription
    from apps.users.models import User

    def log(message):
        if stdout:
            stdout.write(message)
        else:
            print(message)

    # created_by for seeded JDs: the demo admin, else any superuser.
    creator = (
        User.objects.filter(email="ats@admin.com").first()
        or User.objects.filter(is_superuser=True).first()
    )
    if not creator:
        log("ERROR: No admin/superuser found. Run seed_demo_users.py first.")
        return

    # ------------------------------------------------------------------
    # 1) Clients
    # ------------------------------------------------------------------
    clients_by_name = {}
    for c in CLIENTS:
        client, created = Client.objects.update_or_create(
            name=c["name"],
            defaults={
                "email": c["email"],
                "phone": c["phone"],
                "website": c["website"],
                "description": c["description"],
            },
        )
        clients_by_name[client.name] = client
        log(f"{'Created' if created else 'Updated'} client: {client.name}")

    # ------------------------------------------------------------------
    # 2) Job Descriptions (keyed by title + client for idempotency)
    # ------------------------------------------------------------------
    for jd_data in JDS:
        client = clients_by_name[jd_data["client"]]
        defaults = {
            "department": jd_data["department"],
            "location": jd_data["location"],
            "experience_band": jd_data["experience_band"],
            "ctc_band": jd_data["ctc_band"],
            "notice_period": jd_data["notice_period"],
            "shift": jd_data["shift"],
            "working_days": jd_data["working_days"],
            "num_positions": jd_data["num_positions"],
            "status": jd_data["status"],
            "priority": jd_data["priority"],
            "must_have_skills": jd_data["must_have_skills"],
            "good_to_have_skills": jd_data["good_to_have_skills"],
            "qualifications": jd_data["qualifications"],
            "certification": jd_data["certification"],
            "questions": jd_data["questions"],
            "work_details": jd_data["work_details"],
            "created_by": creator,
        }
        # Keep workflow state consistent: Published/Closed JDs were approved.
        if jd_data["status"] in ("Published", "Closed"):
            defaults["approval_status"] = "APPROVED"
            defaults["approved_at"] = timezone.now()
            defaults["approved_by"] = creator
        else:
            defaults["approval_status"] = "DRAFT"

        jd, created = JobDescription.objects.update_or_create(
            title=jd_data["title"],
            client=client,
            defaults=defaults,
        )
        log(f"{'Created' if created else 'Updated'} JD: {jd.title} ({client.name})")

    log("Client & JD seeding completed successfully!")
    log(f"Totals now in DB: {Client.objects.count()} clients, {JobDescription.objects.count()} JDs")


if __name__ == "__main__":
    # Set up Django
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")
    django.setup()

    seed_data()
