"""Restore provenance on ModelQuestion via Fellegi-Sunter record linkage.

Reads a Gemini-extracted questions-only JSON for one paper; matches each
incoming question to an existing ModelQuestion row on text similarity;
fills source_ref / chapter / marks on strong matches; queues mid-range
matches for teacher review.

NEVER touches model_answer (ALCOA+ Original).
Never creates rows (that is ingest_model_paper's job — Rule 10).

Buckets:
  >= 0.90  ->  match_status='auto', needs_teacher_review=False
  0.70-0.89 -> match_status='queue', needs_teacher_review=True
  < 0.70   ->  report only, no DB write

Standards:
  Fellegi & Sunter 1969 (Record Linkage)
  ISO 8000-110 (Master Data Quality)
  ISO/IEC 19788-1 (MLR metadata)
  ALCOA+ Original
  Rule 9 (log first, delete second); Rule 10 (one canonical writer); Rule 24.
"""
import json
import re
from decimal import Decimal
from pathlib import Path as _Path

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import timezone

from exams.models import ModelPaper, ModelQuestion


STRONG = Decimal("0.90")
MID    = Decimal("0.70")


def _norm(s):
    """Normalize text: lowercase, collapse whitespace, strip punctuation."""
    if s is None:
        return ""
    t = str(s).lower()
    t = re.sub(r"[^\w\s]+", " ", t)
    t = re.sub(r"\s+", " ", t).strip()
    return t


def _tokens(s):
    return set(_norm(s).split())


def _jaccard(a, b):
    if not a or not b:
        return 0.0
    return len(a & b) / len(a | b)


def _extract_questions(data):
    """Best-effort question extraction from a Gemini stage0 JSON.

    Accepts three shapes:
      {"questions":[{question_text,...},...]}
      {"sections":[{"items":[...]},...]}
      {"sections":[{"questions":[...]},...]}
    Returns a list of dicts; each dict has question_text + optional
    source_ref / chapter / marks.
    """
    out = []
    if isinstance(data, dict):
        if isinstance(data.get("questions"), list):
            out = list(data["questions"])
        elif isinstance(data.get("sections"), list):
            for sec in data["sections"]:
                if not isinstance(sec, dict):
                    continue
                for key in ("items", "questions"):
                    if isinstance(sec.get(key), list):
                        out.extend(sec[key])
                        break
    out = [q for q in out if isinstance(q, dict)]
    return out


class Command(BaseCommand):
    help = "Fellegi-Sunter text matching to fill ModelQuestion provenance."

    def add_arguments(self, parser):
        parser.add_argument("--file", required=True, help="Path to questions-only JSON")
        parser.add_argument("--subject", required=False, default="",
                            help="Subject prefix (e.g. MT-9). Omit to auto-detect from the JSON code field.")
        parser.add_argument("--dry-run", action="store_true",
                            help="Report only; no DB writes")

    def handle(self, *args, **opts):
        path = _Path(opts["file"])
        if not path.exists():
            raise CommandError(f"File not found: {path}")
        data = json.loads(path.read_text(encoding="utf-8"))
        subject = (opts.get("subject") or "").strip().upper()
        # Auto-detect from fixture code field: 'CH-9-P33' -> 'CH-9'
        if not subject:
            raw_code = (data.get("code") or "").strip().upper()
            import re as _re
            m = _re.match(r"^([A-Z]{2}-9)", raw_code)
            if m:
                subject = m.group(1)
                self.stdout.write(f"auto-detected subject={subject!r} from code={raw_code!r}")
        if not subject:
            raise CommandError("No --subject given and no code field found in JSON")
        dry = opts["dry_run"]
        incoming = _extract_questions(data)
        if not incoming:
            raise CommandError("No questions found in JSON (checked questions/sections)")

        # Filter ModelQuestions to the requested subject via paper.code prefix.
        # ModelPaper has a code like 'MT-9-P25'; subject prefix is 'MT-9'.
        # Match every ModelPaper whose code IS the subject ("CH-9") OR
        # whose code starts with the subject + dash ("CH-9-P33"). Union.
        # Rule 4 (verify on disk — respect both code forms actually present).
        from django.db.models import Q as _Q
        qs = (
            ModelQuestion.objects
            .select_related("paper")
            .filter(_Q(paper__code__iexact=subject) |
                    _Q(paper__code__istartswith=subject + "-"))
        )
        # Prepare candidate tokens once
        candidates = [
            (q, _tokens(q.question_text or ""))
            for q in qs
        ]

        result = {
            "at": timezone.now().isoformat(),
            "file": str(path),
            "subject": subject,
            "incoming_count": len(incoming),
            "candidates_count": len(candidates),
            "auto": [], "queue": [], "skipped": [],
            "applied": False,
            "dry_run": dry,
        }

        # Compute matches first (no writes)
        assignments = []  # (question_obj, score, incoming)
        for inc in incoming:
            inc_text = inc.get("question_text") or inc.get("text") or ""
            inc_toks = _tokens(inc_text)
            if not inc_toks:
                result["skipped"].append({"reason": "empty text", "incoming": inc})
                continue
            best_q, best_score = None, 0.0
            for q, qtoks in candidates:
                s = _jaccard(inc_toks, qtoks)
                if s > best_score:
                    best_score, best_q = s, q
            score_d = Decimal(str(round(best_score, 2)))
            if best_q is None or score_d < MID:
                result["skipped"].append({
                    "score": float(score_d),
                    "text_head": _norm(inc_text)[:80],
                })
                continue
            if score_d >= STRONG:
                result["auto"].append({
                    "question_id": best_q.id,
                    "score": float(score_d),
                    "text_head": _norm(inc_text)[:80],
                })
            else:
                result["queue"].append({
                    "question_id": best_q.id,
                    "score": float(score_d),
                    "text_head": _norm(inc_text)[:80],
                })
            assignments.append((best_q, score_d, inc))

        if not dry:
            with transaction.atomic():
                for q, score_d, inc in assignments:
                    q.match_score = score_d
                    q.matched_to = None  # self-FK; left null when the row IS the canonical
                    if score_d >= STRONG:
                        q.match_status = "auto"
                        q.needs_teacher_review = False
                        # Fill provenance from incoming where present
                        src = (inc.get("source_ref") or "").strip()
                        ch  = (inc.get("chapter") or "").strip()
                        mrk = inc.get("marks")
                        if src and not q.source_ref:
                            q.source_ref = src[:60]
                        if ch and not q.chapter:
                            q.chapter = ch[:200]
                        if isinstance(mrk, int) and mrk > 0:
                            q.marks = mrk
                    else:
                        q.match_status = "queue"
                        q.needs_teacher_review = True
                    # NEVER touches model_answer (ALCOA+ Original)
                    q.save(update_fields=[
                        "match_score", "matched_to", "match_status",
                        "needs_teacher_review", "source_ref", "chapter", "marks",
                    ])
            result["applied"] = True

        # Write report
        base = _Path("/home/orkoworo/idealogy/tmp")
        base.mkdir(parents=True, exist_ok=True)
        ts = timezone.now().strftime("%Y%m%dT%H%M%SZ")
        report = base / f"link_provenance_{ts}.json"
        report.write_text(json.dumps(result, indent=2) + "\n")

        self.stdout.write(self.style.SUCCESS(
            f"link_provenance: incoming={len(incoming)} "
            f"candidates={len(candidates)} "
            f"auto={len(result['auto'])} "
            f"queue={len(result['queue'])} "
            f"skip={len(result['skipped'])} "
            f"dry={dry} report={report.name}"
        ))
