"""reconcile_pipelines — advance a pipeline's stages_completed from its tasks.

DEF-049 (2026-10-09): KC ladder tasks created by rebalance_kc_ladder_tasks
carried no pipeline FK. The pipeline-advance auto-chain only fires on tasks
with pipeline=pipe, pipeline_stage=N, so those pipelines stalled at stage 7
forever. This command reads the student's own tasks by task_type + subject
prefix and advances any stage whose tasks are all DONE.

Turn 5b-2 (2026-10-10) — PIPELINE ISOLATION:
  Command now requires explicit scope. Default is now REFUSE.
    --code <PAPER_CODE>            advance ONE pipeline (recommended)
    --all-pipelines --reason ".."  advance ALL pipelines (system-wide)
  Apply path runs inside a single transaction; each pipeline row is locked
  via select_for_update() before being written.

Usage:
    python manage.py reconcile_pipelines --code MT-9-BOOK
    python manage.py reconcile_pipelines --code MT-9-BOOK --apply
    python manage.py reconcile_pipelines --all-pipelines --reason "sweep" --apply

Standards: design/ISOLATION-v1.0.md; Kleppmann DDIA 2017 Ch. 7 (transactions
and optimistic concurrency); Fowler PoEAA 2002 Ch. 11 (Unit of Work);
MySQL 8.0 Ref. Manual 15.7.2 (InnoDB row-level locking); AWS Well-Architected
REL05-BP01 (Cell-Based Architecture); Saltzer & Schroeder 1975 (fail-safe
default); Rule 4; Rule 9; Rule 10; Rule 23; Rule 24; Rule 25; Rule 26;
Rule 28; ISO 9001:2015 9.1.2; Google SRE Ch. 17.
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from exams.models import TaskPipeline, StudentTask
from exams.views import PIPELINE_STAGES

STAGE_TO_TT = {1: "BOOK_INGEST", 3: "KC_DISCOVERY", 5: "KC_TAG",
               6: "KC_MISCONCEPTION", 7: "KC_SOCRATIC_LADDER",
               10: "GLOSSARY", 11: "STORY"}
TEACHER_STAGES = {2, 4, 8, 9}


def _sub(paper_code):
    return paper_code.split("-")[0].upper()


def _stage_state(pipe, owner, stage_n):
    """True=DONE, False=open, None=no matching tasks (skip)."""
    tt = STAGE_TO_TT.get(stage_n)
    if not tt:
        return None
    subj = _sub(pipe.paper_code)
    bank_code = subj + "-9"
    if tt == "BOOK_INGEST":
        qs = StudentTask.objects.filter(pipeline=pipe, task_type=tt,
                                        task_ref__startswith=pipe.paper_code)
    elif tt in ("KC_DISCOVERY", "KC_TAG"):
        qs = StudentTask.objects.filter(pipeline=pipe, task_type=tt,
                                        task_ref__startswith=bank_code)
    else:
        qs = StudentTask.objects.filter(pipeline=pipe, task_type=tt,
                                        task_ref__startswith="C9-" + subj)
    if not qs.exists():
        return None
    # Turn 22 (2026-10-11) - a stage is COMPLETE when all its tasks are
    # resolved: either DONE (finished) or SKIPPED (explicitly retired).
    # This is the standard Stage-Gate definition of exit criteria: work is
    # resolved, not only completed.
    # Standards: Cooper Stage-Gate; ALCOA+ (retired work preserved with
    # reason); Rule 9 (status change always logged); ISO/IEC/IEEE 29119-3 5.4.
    return all(t.status in ("DONE", "SKIPPED") for t in qs)


class Command(BaseCommand):
    help = "Advance pipeline stages_completed from the owner's own task state."

    def add_arguments(self, p):
        p.add_argument("--code", type=str, default=None,
                       help="Paper code of ONE pipeline (e.g. MT-9-BOOK).")
        p.add_argument("--all-pipelines", action="store_true",
                       help="Advance ALL pipelines. Requires --reason.")
        p.add_argument("--reason", default=None,
                       help="Justification for --all-pipelines (>=20 chars).")
        p.add_argument("--apply", action="store_true",
                       help="Write changes. Default: dry-run.")

    def _process(self, qs, apply_writes):
        changed = 0
        for p in qs:
            owner = p.owner_student
            if not owner:
                continue
            before = set(p.stages_completed or [])
            completed = set(before)
            for n, _lbl, _who, _ai in PIPELINE_STAGES:
                if n in completed:
                    continue
                r = _stage_state(p, owner, n)
                if r is True:
                    completed.add(n)
            next_n = None
            for n, _lbl, _who, _ai in PIPELINE_STAGES:
                if n not in completed:
                    next_n = n
                    break
            if next_n is None:
                new_status = "DONE"; next_n = 11
            elif next_n in TEACHER_STAGES:
                new_status = "BLOCKED_ON_TEACHER"
            else:
                new_status = "ACTIVE"
            if (completed == before) and (p.current_stage == next_n) and (p.status == new_status):
                continue
            self.stdout.write("  %s  owner=%s  done=%s -> %s  stage=%s -> %s  status=%s -> %s" % (
                p.paper_code, owner.code,
                sorted(before), sorted(completed),
                p.current_stage, next_n, p.status, new_status))
            changed += 1
            if apply_writes:
                # Lock the pipeline row (Turn 5b-2; Kleppmann DDIA Ch.7;
                # MySQL 8.0 Ref. Manual 15.7.2).
                pl = TaskPipeline.objects.select_for_update().get(id=p.id)
                pl.stages_completed = sorted(completed)
                pl.current_stage = next_n
                pl.status = new_status
                pl.save(update_fields=["stages_completed", "current_stage",
                                       "status", "updated_at"])
                # Auto-create next-stage task if student stage.
                if next_n in STAGE_TO_TT and next_n not in TEACHER_STAGES:
                    tt_next = STAGE_TO_TT[next_n]
                    if tt_next == "BOOK_INGEST":
                        pass
                    elif tt_next in ("KC_DISCOVERY", "KC_TAG"):
                        ref_next = _sub(pl.paper_code) + "-9"
                        exists = (StudentTask.objects
                                  .filter(student=owner, task_type=tt_next,
                                          task_ref__startswith=ref_next)
                                  .exclude(status="SKIPPED").exists())
                        if not exists:
                            StudentTask.objects.create(
                                student=owner, task_type=tt_next,
                                task_ref=ref_next, status="ASSIGNED",
                                category="MANAGEMENT",
                                pipeline=pl, pipeline_stage=next_n,
                                notes=f"[auto] stage {next_n} unlocked by reconcile",
                            )
        return changed

    def handle(self, *args, **o):
        # Turn 5b-2 scope check (design/ISOLATION-v1.0.md; Rule 28;
        # Saltzer & Schroeder 1975 — fail-safe default).
        code = (o.get("code") or "").strip().upper()
        all_pipelines = bool(o.get("all_pipelines"))
        reason = (o.get("reason") or "").strip()

        if code and all_pipelines:
            raise CommandError("Choose one: --code OR --all-pipelines")
        if not code and not all_pipelines:
            raise CommandError(
                "Refused: no scope. Use --code <PAPER_CODE> (recommended) "
                "or --all-pipelines --reason '...' (>=20 chars). "
                "Standards: Rule 25; design/ISOLATION-v1.0.md."
            )
        if all_pipelines and len(reason) < 20:
            raise CommandError("--all-pipelines requires --reason with >= 20 chars.")

        if all_pipelines:
            self.stdout.write("SCOPE: ALL pipelines (reason=" + reason + ")")
        else:
            self.stdout.write("SCOPE: pipeline " + code)

        qs = TaskPipeline.objects.all().order_by("paper_code")
        if code:
            qs = qs.filter(paper_code=code)
            if not qs.exists():
                raise CommandError("no TaskPipeline with paper_code=" + code)

        if o["apply"]:
            with transaction.atomic():
                changed = self._process(qs, apply_writes=True)
        else:
            changed = self._process(qs, apply_writes=False)

        self.stdout.write("changed=%d  applied=%s"
                          % (changed, "yes" if o["apply"] else "no (dry-run)"))
