"""detect_kc_defects - scan KC pipeline entities for ISO 8000 defects.

Design: design/KC-DATA-QUALITY-REMEDIATION-v1.0.md
Standards: ISO 8000-8 5.2-5.5; ISO 8000-61; DAMA-DMBOK2 Ch.13;
ALCOA+ Original; Rule 9; Rule 14; Rule 24; Rule 28.

Six detectors:
  MISSING       required field blank
  WRONG         placeholder token found
  INCONSISTENT  same question_text, conflicting model_answer
  DUPLICATE     same question_text, multiple live rows
  MALFORMED     kc_code / marks fail schema
  ORPHAN        kc_code does not match a live KC

Idempotent: an existing OPEN/IN_PROGRESS issue for the same
(entity_type, entity_id, defect_class) is not duplicated.
"""
import re
from pathlib import Path

from django.core.management.base import BaseCommand
from django.db.models import Count

from exams.models import (
    ModelQuestion, ModelPaper, KnowledgeComponent, DataQualityIssue,
)

PLACEHOLDER_PAT = re.compile(
    r"\b(TODO|TBD|FIXME|XXX|PLACEHOLDER|\?\?\?)\b", re.IGNORECASE
)
KC_CODE_PAT = re.compile(r"^C9-[A-Z]{2}[0-9A-Z-]*$")


def _existing_issue_keys():
    """Preload (entity_type, entity_id, defect_class) for open issues."""
    rows = DataQualityIssue.objects.filter(
        status__in=["OPEN", "TASK_ASSIGNED", "IN_PROGRESS"]
    ).values_list("entity_type", "entity_id", "defect_class")
    return set(rows)


class Command(BaseCommand):
    help = "Scan KC pipeline entities for defects; create DataQualityIssue rows."

    def add_arguments(self, parser):
        parser.add_argument("--dry-run", action="store_true",
                            help="Report only; do not write.")
        parser.add_argument("--severity", choices=["BLOCKER", "MAJOR", "MINOR"],
                            help="Filter created issues (default: all).")
        parser.add_argument("--daily-only", action="store_true",
                            help="Run at most once per UTC day (marker file).")

    def handle(self, *args, **opts):
        dry = opts["dry_run"]
        if opts.get("daily_only"):
            from django.conf import settings as _s
            from datetime import date as _d
            marker = Path(_s.BASE_DIR).parent / "tmp" / "dq_last_scan.txt"
            today = _d.today().isoformat()
            if marker.exists() and marker.read_text(encoding="utf-8").strip() == today:
                self.stdout.write("daily-only: already scanned today (" + today + ")")
                return
            marker.parent.mkdir(parents=True, exist_ok=True)
            marker.write_text(today, encoding="utf-8")
        sev_filter = opts.get("severity")
        existing = _existing_issue_keys()
        created = []
        skipped = 0

        def emit(entity_type, entity_id, defect_class, severity, evidence):
            nonlocal skipped
            if sev_filter and severity != sev_filter:
                return
            key = (entity_type, entity_id, defect_class)
            if key in existing:
                skipped += 1
                return
            existing.add(key)
            created.append(DataQualityIssue(
                entity_type=entity_type, entity_id=entity_id,
                defect_class=defect_class, severity=severity,
                evidence=evidence,
            ))

        # ---------- ModelQuestion ----------
        qs = ModelQuestion.objects.filter(superseded_at__isnull=True)
        for q in qs.iterator():
            if not (q.question_text or "").strip():
                emit("ModelQuestion", q.id, "MISSING", "BLOCKER",
                     {"field": "question_text"})
            if not (q.model_answer or "").strip():
                emit("ModelQuestion", q.id, "MISSING", "BLOCKER",
                     {"field": "model_answer"})
            if q.question_text and PLACEHOLDER_PAT.search(q.question_text):
                emit("ModelQuestion", q.id, "WRONG", "MAJOR",
                     {"field": "question_text",
                      "match": PLACEHOLDER_PAT.search(q.question_text).group(0)})
            if q.model_answer and PLACEHOLDER_PAT.search(q.model_answer):
                emit("ModelQuestion", q.id, "WRONG", "MAJOR",
                     {"field": "model_answer",
                      "match": PLACEHOLDER_PAT.search(q.model_answer).group(0)})
            if q.kc_code and not KC_CODE_PAT.match(q.kc_code):
                emit("ModelQuestion", q.id, "MALFORMED", "MAJOR",
                     {"field": "kc_code", "value": q.kc_code})
            if q.marks is None or q.marks < 1 or q.marks > 50:
                emit("ModelQuestion", q.id, "MALFORMED", "MINOR",
                     {"field": "marks", "value": q.marks})

        # ORPHAN: kc_code not matching a live KC
        live_kcs = set(KnowledgeComponent.objects
                       .filter(is_active=True)
                       .values_list("code", flat=True))
        for q in qs.exclude(kc_code="").only("id", "kc_code"):
            if q.kc_code and q.kc_code not in live_kcs:
                emit("ModelQuestion", q.id, "ORPHAN", "MAJOR",
                     {"field": "kc_code", "value": q.kc_code})

        # DUPLICATE / INCONSISTENT by question_text
        dup_texts = (qs.exclude(question_text="")
                     .values("question_text")
                     .annotate(n=Count("id"))
                     .filter(n__gt=1))
        for row in dup_texts:
            text = row["question_text"]
            ids = list(qs.filter(question_text=text).values_list("id", flat=True))
            answers = set(qs.filter(question_text=text)
                          .values_list("model_answer", flat=True))
            if len(answers) > 1:
                for qid in ids[1:]:
                    emit("ModelQuestion", qid, "INCONSISTENT", "BLOCKER",
                         {"question_text": text[:200],
                          "distinct_answers": len(answers)})
            else:
                for qid in ids[1:]:
                    emit("ModelQuestion", qid, "DUPLICATE", "MAJOR",
                         {"question_text": text[:200]})

        # ---------- ModelPaper ----------
        for p in ModelPaper.objects.iterator():
            if not (p.code or "").strip():
                emit("ModelPaper", p.id, "MISSING", "BLOCKER", {"field": "code"})
            if not (p.subject or "").strip():
                emit("ModelPaper", p.id, "MISSING", "BLOCKER", {"field": "subject"})
            if not (p.title or "").strip():
                emit("ModelPaper", p.id, "MISSING", "MINOR", {"field": "title"})

        # ---------- KnowledgeComponent ----------
        for k in KnowledgeComponent.objects.filter(is_active=True).iterator():
            if not (k.code or "").strip():
                emit("KnowledgeComponent", k.id, "MISSING", "BLOCKER", {"field": "code"})
            if not (k.subject or "").strip():
                emit("KnowledgeComponent", k.id, "MISSING", "BLOCKER", {"field": "subject"})
            if not (k.title or "").strip():
                emit("KnowledgeComponent", k.id, "MISSING", "MAJOR", {"field": "title"})
            if k.code and not KC_CODE_PAT.match(k.code):
                emit("KnowledgeComponent", k.id, "MALFORMED", "MAJOR",
                     {"field": "code", "value": k.code})

        # ---------- Write ----------
        if dry:
            self.stdout.write(f"DRY-RUN: would create {len(created)} issue(s); "
                              f"skipped existing {skipped}")
            by_class = {}
            for d in created:
                by_class[d.defect_class] = by_class.get(d.defect_class, 0) + 1
            for k in sorted(by_class):
                self.stdout.write(f"  {k}: {by_class[k]}")
            return

        DataQualityIssue.objects.bulk_create(created, batch_size=500)
        self.stdout.write(self.style.SUCCESS(
            f"created {len(created)} issue(s); skipped existing {skipped}"))
