"""pipeline_audit - per-pipeline, per-stage task trail with evidence.

Standards: ISO 8000-8 5.2-5.5; ALCOA+ Complete; ISO 27001 A.8.15;
Rule 9; Rule 25; Cooper Stage-Gate. Read-only report + --fix to repair.
"""
import json
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path

from django.core.management.base import BaseCommand
from exams.models import (StudentTask, TaskPipeline, Student,
                          CorrectionLog, PortalFeatureLog)

EXPECTED_STUDENT_STAGES = [1, 3, 5, 6, 7, 10, 11]
STAGE_LABEL = {
    1: "BOOK_INGEST", 3: "KC_DISCOVERY", 5: "KC_TAG",
    6: "KC_MISCONCEPTION", 7: "KC_SOCRATIC_LADDER",
    10: "GLOSSARY", 11: "STORY",
}
REASON_SUPERSEDED = "superseded 2026-10: KC-level workflow replaced raw page ingestion (see SESSION-2026-10-12-HANDOFF.md Part 4)"


class Command(BaseCommand):
    help = "Audit every pipeline stage trail; optionally fix."
    def add_arguments(self, p):
        p.add_argument("--fix", action="store_true")
        p.add_argument("--out", default="/home/orkoworo/idealogy/tmp/pipeline_audit.json")

    def handle(self, *a, **o):
        fix = o["fix"]
        now = datetime.now(timezone.utc).isoformat()
        evidence = {"when": now, "pipelines": [], "fixes": []}

        for p in TaskPipeline.objects.order_by("paper_code"):
            owner = p.owner_student
            if owner is None:
                continue
            tasks = list(StudentTask.objects.filter(pipeline=p))
            by_stage = defaultdict(list)
            for t in tasks:
                by_stage[t.pipeline_stage or 0].append(t)

            expected_for_stage = [s for s in EXPECTED_STUDENT_STAGES
                                  if s <= p.current_stage]
            present = sorted(s for s in by_stage if s in EXPECTED_STUDENT_STAGES)
            missing = sorted(set(expected_for_stage) - set(present))

            stage_rows = []
            for stage in sorted(by_stage):
                if stage not in EXPECTED_STUDENT_STAGES:
                    continue
                rs = by_stage[stage]
                done = sum(1 for t in rs if t.status == "DONE")
                skipped = sum(1 for t in rs if t.status == "SKIPPED")
                live = sum(1 for t in rs if t.status in ("ASSIGNED", "IN_PROGRESS"))
                no_reason = sum(1 for t in rs if t.status == "SKIPPED"
                                and not (t.ingest_error or "").strip())
                failed = sum(1 for t in rs if t.ingest_status == "FAILED")
                stage_rows.append({
                    "stage": stage, "label": STAGE_LABEL.get(stage, ""),
                    "total": len(rs), "done": done, "skipped": skipped,
                    "live": live, "no_reason_skipped": no_reason,
                    "failed": failed,
                })

            evidence["pipelines"].append({
                "paper_code": p.paper_code, "owner": owner.code,
                "current_stage": p.current_stage,
                "expected_stages_so_far": expected_for_stage,
                "present_stages": present, "missing_stages": missing,
                "stages": stage_rows,
            })

            if fix:
                # 1. add reason to SKIPPED stage-1 with no reason
                for stage in (1,):
                    for t in by_stage.get(stage, []):
                        if (t.status == "SKIPPED"
                                and not (t.ingest_error or "").strip()):
                            t.ingest_error = REASON_SUPERSEDED
                            t.save(update_fields=["ingest_error"])
                            CorrectionLog.objects.create(
                                kind="MODEL", target_model="StudentTask",
                                target_id=t.id, field_name="ingest_error",
                                old_value="", new_value=REASON_SUPERSEDED[:120],
                                reason="Rule 9 retrofit: skipped with documented reason",
                                actor_label="terminal:teacher")
                            evidence["fixes"].append(
                                {"action": "add_reason", "task": t.id,
                                 "student": owner.code, "stage": stage})

                # 2. Hamid's FAILED KC_MISCONCEPTION: reset to ASSIGNED
                for stage in (6,):
                    for t in by_stage.get(stage, []):
                        if t.ingest_status == "FAILED":
                            t.status = "ASSIGNED"
                            t.ingest_status = "PENDING"
                            t.ingest_error = ((t.ingest_error or "")[:300]
                                + " | reset 2026-10-12 after FAILED")
                            t.save(update_fields=["status", "ingest_status",
                                                  "ingest_error"])
                            CorrectionLog.objects.create(
                                kind="MODEL", target_model="StudentTask",
                                target_id=t.id, field_name="status",
                                old_value="FAILED", new_value="ASSIGNED",
                                reason="Retry after FAILED (Rule 24)",
                                actor_label="terminal:teacher")
                            evidence["fixes"].append(
                                {"action": "reset_failed", "task": t.id,
                                 "student": owner.code})

                # 3. BI-9-BOOK stage 1 LIVE rows -> SKIPPED with reason
                if p.paper_code == "BI-9-BOOK":
                    for t in by_stage.get(1, []):
                        if t.status in ("ASSIGNED", "IN_PROGRESS"):
                            t.status = "SKIPPED"
                            t.ingest_status = "PENDING"
                            t.ingest_error = REASON_SUPERSEDED
                            t.save(update_fields=["status", "ingest_status",
                                                  "ingest_error"])
                            CorrectionLog.objects.create(
                                kind="MODEL", target_model="StudentTask",
                                target_id=t.id, field_name="status",
                                old_value=t.status, new_value="SKIPPED",
                                reason="Stage-1 superseded; documented per Rule 9",
                                actor_label="terminal:teacher")
                            evidence["fixes"].append(
                                {"action": "skip_superseded", "task": t.id,
                                 "student": owner.code})

        out = Path(o["out"])
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(evidence, indent=2) + chr(10), encoding="utf-8")
        self.stdout.write(f"wrote {out}")
        self.stdout.write(f"pipelines: {len(evidence['pipelines'])}  "
                          f"fixes: {len(evidence['fixes'])}")
        # print summary
        for row in evidence["pipelines"]:
            self.stdout.write(f"  {row['paper_code']} ({row['owner']}) "
                              f"stage={row['current_stage']} "
                              f"missing={row['missing_stages']}")
