"""reconcile_kc_tasks - mark fail-state KC_* tasks as SKIPPED (never delete).

Scans open KC_TAG / KC_DISCOVERY / KC_MISCONCEPTION / KC_SOCRATIC_LADDER
tasks and applies the same subject-scope classifier the fixed writer uses.

Fail states (any of):
  kc_missing            task_ref does not resolve to a KnowledgeComponent
  subject_unmapped      KC.subject not in the prefix map
  student_no_enrollment student has no BOOK_INGEST refs and no Exam rows
  subject_mismatch      KC prefix not in student's enrolled set

Action on fail states: status -> SKIPPED; reason appended to notes.
Never deletes (Rule 9). Default is dry-run; --apply is required to write.

Turn 4 (2026-10-10) - PIPELINE ISOLATION:
  Command now requires explicit scope. Default behaviour is now REFUSE.
    --pipeline <paper_code>       reconcile ONE pipeline (recommended)
    --all-pipelines --reason ".." reconcile ALL pipelines (system-wide)
  Scoped runs lock only the target TaskPipeline row via select_for_update.
  --all-pipelines writes a JSONL audit line to tmp/reconcile_kc_tasks_log.jsonl
  AFTER a successful write (Rule 9 + Section 3.6 correction).

Standards: design/ISOLATION-v1.0.md; Kleppmann DDIA 2017 Ch. 7
(optimistic concurrency); Fowler PoEAA 2002 Ch. 11 (Unit of Work);
AWS Well-Architected REL05-BP01 (Cell-Based Architecture); Azure
Architecture Center (Bulkhead Pattern); MySQL 8.0 Ref. Manual 15.7.2
(InnoDB row-level locking); Saltzer & Schroeder 1975 (fail-safe default);
Rule 9 (log first, delete second); Rule 10 (one canonical writer);
Rule 23 (dry-run default, explicit --apply); Rule 24 (sandbox first);
Rule 25 (one task one owner); Rule 28 (standards above directive);
NIST SP 800-53 SI-10; AERA/APA/NCME 2014 Std 1.0; ISO 27001 A.8.15;
ISO 21500:2021 4.3.3; ISO/IEC/IEEE 29119-3; Womack & Jones Lean Thinking.
"""
import json
from datetime import datetime, timezone
from pathlib import Path

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from exams.models import StudentTask, KnowledgeComponent, Exam, TaskPipeline

PFX = {"Mathematics": "MT", "Physics": "PH", "Chemistry": "CH",
       "Biology": "BI", "English": "EN", "Urdu": "UR",
       "Islamiyat": "IS", "Computer Science": "CS",
       "Tarjumatul Quran": "TQ"}

KC_TYPES = ("KC_TAG", "KC_DISCOVERY", "KC_MISCONCEPTION", "KC_SOCRATIC_LADDER")
OPEN_STATES = ("ASSIGNED", "IN_PROGRESS")

AUDIT_LOG = Path(settings.BASE_DIR).parent / "tmp" / "reconcile_kc_tasks_log.jsonl"


def _enrolled(student):
    """Thin shim - delegates to the canonical reader (Rule 10)."""
    from exams.enrollment import enrolled_prefixes
    return enrolled_prefixes(student)


def _classify(task):
    # KC_TAG / KC_DISCOVERY use a PAPER code as task_ref, not a KC code.
    # Only KC_MISCONCEPTION / KC_SOCRATIC_LADDER reference a KC.
    # Standards: Rule 4; Rule 10; ISO/IEC/IEEE 29119-3 5.4.
    if task.task_type in ("KC_TAG", "KC_DISCOVERY"):
        e = _enrolled(task.student)
        if not e:
            return "student_no_enrollment", ("student " + task.student.code
                                             + " has no enrolled subjects")
        return "ok", ""
    kc = KnowledgeComponent.objects.filter(code=task.task_ref).first()
    if not kc:
        return "kc_missing", "KC not found: " + str(task.task_ref)
    pfx = PFX.get(kc.subject or "", "")
    if not pfx:
        return "subject_unmapped", "KC subject not mapped: " + repr(kc.subject)
    e = _enrolled(task.student)
    if not e:
        return "student_no_enrollment", ("student " + task.student.code
                                         + " has no enrolled subjects")
    if pfx not in e:
        return "subject_mismatch", ("KC subject " + kc.subject + " (" + pfx
                                    + ") not in student " + task.student.code
                                    + " enrolled subjects " + str(sorted(e)))
    return "ok", ""


class Command(BaseCommand):
    help = "Mark fail-state KC_* tasks as SKIPPED (never deletes)."

    def add_arguments(self, parser):
        parser.add_argument("--apply", action="store_true",
                            help="Actually mark SKIPPED (default: dry-run).")
        parser.add_argument("--task-type", default=None,
                            help="Restrict to one KC_* type.")
        parser.add_argument("--pipeline", default=None,
                            help="Paper code (e.g. MT-9-BOOK). Scope to one pipeline.")
        parser.add_argument("--all-pipelines", action="store_true",
                            help="Operate across ALL pipelines. Requires --reason.")
        parser.add_argument("--reason", default=None,
                            help="Justification for --all-pipelines (>=20 chars).")

    def handle(self, *args, **opts):
        # ---- Turn 4: fail-safe scope check (Rule 28; Saltzer & Schroeder 1975) ----
        pipeline_code = (opts.get("pipeline") or "").strip().upper() or None
        all_pipelines = bool(opts.get("all_pipelines"))
        reason = (opts.get("reason") or "").strip()

        if pipeline_code and all_pipelines:
            raise CommandError("Choose one: --pipeline OR --all-pipelines")
        if not pipeline_code and not all_pipelines:
            raise CommandError(
                "Refused: no scope. Use --pipeline <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 opts["task_type"] and opts["task_type"] not in KC_TYPES:
            raise CommandError("unknown --task-type: " + opts["task_type"])
        types = (opts["task_type"],) if opts["task_type"] else KC_TYPES
        dry = not opts["apply"]

        # ---- Resolve scope ----
        pipeline_row = None
        if pipeline_code:
            pipeline_row = TaskPipeline.objects.filter(paper_code=pipeline_code).first()
            if not pipeline_row:
                raise CommandError("no TaskPipeline with paper_code=" + pipeline_code)
            self.stdout.write("SCOPE: pipeline " + pipeline_code
                              + " (id=" + str(pipeline_row.id) + ")")
        else:
            self.stdout.write("SCOPE: ALL pipelines (reason=" + reason + ")")

        base_qs = StudentTask.objects.filter(
            task_type__in=types, status__in=OPEN_STATES)
        if pipeline_code:
            base_qs = base_qs.filter(pipeline_id=pipeline_row.id)

        counts = {}
        to_skip = []
        for t in base_qs:
            cls, reason_txt = _classify(t)
            counts[(t.task_type, cls)] = counts.get((t.task_type, cls), 0) + 1
            if cls != "ok":
                to_skip.append((t, cls, reason_txt))

        self.stdout.write("=== classification ===")
        for k in sorted(counts):
            self.stdout.write("  " + str(k) + "  " + str(counts[k]))

        self.stdout.write("=== fail-state rows: " + str(len(to_skip)) + " ===")
        for t, cls, reason_txt in to_skip[:20]:
            self.stdout.write("  [%s] id=%s student=%s ref=%s :: %s"
                              % (cls, t.pk, t.student.code, t.task_ref, reason_txt))
        if len(to_skip) > 20:
            self.stdout.write("  ... and %d more" % (len(to_skip) - 20))

        if not to_skip and pipeline_code:
            self.stdout.write("(hint: tasks with pipeline_id=NULL are never "
                              "touched by a scoped run; use --all-pipelines "
                              "for a system-wide sweep)")

        if dry:
            self.stdout.write("(DRY RUN - nothing written; pass --apply to mark)")
            return

        # ---- Apply inside a single transaction; lock ONLY the target pipeline ----
        with transaction.atomic():
            if pipeline_code:
                # Lock one pipeline row (Kleppmann DDIA Ch. 7)
                TaskPipeline.objects.select_for_update().filter(
                    id=pipeline_row.id).exists()

            for t, cls, reason_txt in to_skip:
                t.status = "SKIPPED"
                t.notes = ((t.notes or "")
                           + "\n[reconcile 2026-10-10] "
                           + cls + ": " + reason_txt).strip()
                t.save(update_fields=["status", "notes"])

        self.stdout.write("Applied: %d rows marked SKIPPED." % len(to_skip))

        # ---- Section 3.6: audit log AFTER successful write ----
        try:
            AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
            with AUDIT_LOG.open("a", encoding="utf-8") as f:
                f.write(json.dumps({
                    "ts": datetime.now(timezone.utc).isoformat(),
                    "command": "reconcile_kc_tasks",
                    "scope": pipeline_code or "ALL",
                    "reason": reason if all_pipelines else "",
                    "rows_skipped": len(to_skip),
                    "task_types": list(types),
                }) + "\n")
        except Exception:
            pass
