"""page_audit - scan every template against PAGE-AUDIT-STANDARDS-v1.0.md.

Standards: WCAG 2.2 AA; ISO 9241-110/112; Rule G (Roman Urdu);
Section Zero (stepper); Rule 27; Rule 28.
Read-only. Produces JSON + summary table. Exits non-zero on BLOCKER.
"""
import json, re
from pathlib import Path
from datetime import datetime, timezone
from django.core.management.base import BaseCommand
from django.conf import settings

EXEMPT_NO_TOPBAR = {"login.html"}

def _check(name, src):
    issues = []
    lang = re.search(r'<html[^>]*lang="([^"]+)"', src)
    if not lang:
        issues.append(("BLOCKER", "no html lang attr"))
    elif lang.group(1) not in ("ur-Latn", "en"):
        issues.append(("MAJOR", f"lang={lang.group(1)} not ur-Latn or en"))
    if not re.search(r'<title>[^<]+</title>', src):
        issues.append(("MINOR", "no <title>"))
    if "skip" not in src.lower():
        issues.append(("MAJOR", "no skip link"))
    has_tb = any(x in src for x in ("_student_topbar", "_teacher_topbar", "_parent_topbar"))
    if not has_tb and name not in EXEMPT_NO_TOPBAR:
        issues.append(("MAJOR", "no topbar include"))
    if src.count("<h1") > 1:
        issues.append(("MAJOR", "multiple H1"))
    if "<h1" not in src:
        issues.append(("MINOR", "no H1"))
    # english chrome heuristics
    if re.search(r">\s*(Submit|Cancel|Save|Home|Dashboard|Login|Logout|Welcome)\s*<", src):
        issues.append(("MAJOR", "English chrome string in UI"))
    return issues


class Command(BaseCommand):
    help = "Read-only audit of every template vs PAGE-AUDIT-STANDARDS."
    def add_arguments(self, parser):
        parser.add_argument("--role", help="Filter: student|teacher|parent|admin|misc")
        parser.add_argument("--out", default="/home/orkoworo/idealogy/tmp/page_audit.json")
    def handle(self, *args, **opts):
        tpl = Path(settings.BASE_DIR) / "exams" / "templates" / "exams"
        rows = []
        total = Counter = {"BLOCKER": 0, "MAJOR": 0, "MINOR": 0}
        for f in sorted(tpl.glob("*.html")):
            if f.name.startswith("_"):
                continue
            name = f.name
            if "teacher" in name or "wizard" in name:
                role = "teacher"
            elif "parent" in name:
                role = "parent"
            elif "admin" in name:
                role = "admin"
            elif name.startswith("portal_"):
                role = "student"
            else:
                role = "misc"
            if opts["role"] and role != opts["role"]:
                continue
            src = f.read_text(encoding="utf-8", errors="ignore")
            issues = _check(name, src)
            for sev, _ in issues:
                total[sev] += 1
            rows.append({"file": name, "role": role, "issues": issues})
        summary = {
            "when": datetime.now(timezone.utc).isoformat(),
            "n_templates": len(rows),
            "totals": total,
            "rows": rows,
        }
        out = Path(opts["out"])
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(summary, indent=2) + chr(10), encoding="utf-8")
        self.stdout.write(f"audited {len(rows)} templates")
        self.stdout.write(f"  BLOCKER: {total['BLOCKER']}")
        self.stdout.write(f"  MAJOR:   {total['MAJOR']}")
        self.stdout.write(f"  MINOR:   {total['MINOR']}")
        for r in rows:
            if r["issues"]:
                line = r["file"] + " [" + r["role"] + "]:"
                for sev, msg in r["issues"]:
                    line += f" {sev}:{msg};"
                self.stdout.write("  " + line[:200])
        if total["BLOCKER"] > 0:
            raise SystemExit(1)
