"""Seed the AI screening pipeline stages.

Run:  python add_ai_stages.py

Inserts three stages right after 'Candidate Responded' (shifting later
stages' sort_order to make room). Idempotent — re-running only fixes order.

    AI Calling   — outbound call queued/ringing/in progress
    AI Screened  — call done, below the qualify threshold (needs human review)
    AI Qualified — call done, scored at/above the threshold
"""

import django
import os
import sys

AI_STAGES = [
    ("AI Calling", "ai_calling"),
    ("AI Screened", "ai_screened"),
    ("AI Qualified", "ai_qualified"),
]


def add_ai_stages():
    from apps.pipeline.models import PipelineStage

    existing = {s.code for s in PipelineStage.objects.all()}
    missing = [(n, c) for n, c in AI_STAGES if c not in existing]
    if not missing:
        print("AI stages already present — nothing to do.")
        return

    anchor = PipelineStage.objects.filter(code="candidate_responded").first() \
        or PipelineStage.objects.order_by("sort_order", "id").first()
    base = anchor.sort_order if anchor else 0

    # Make room after the anchor for the new stages
    shift = len(missing)
    PipelineStage.objects.filter(sort_order__gt=base).update(
        sort_order=django.db.models.F("sort_order") + shift
    )
    for i, (name, code) in enumerate(missing, start=1):
        PipelineStage.objects.create(
            name=name, code=code, sort_order=base + i,
            outcome=PipelineStage.Outcome.IN_PROGRESS, is_active=True,
        )
        print(f"Created stage '{name}' (sort {base + i}).")


if __name__ == "__main__":
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")
    django.setup()
    import django.db.models  # noqa: F401  (used for F() above after setup)
    add_ai_stages()
