"""Paper 2 Space: MindGuard (arXiv 2602.00950), MindGuard 8B vs Qwen3Guard-Gen-8B (strict).

Reads measured values dynamically from ``results/02-mindguard/metrics.json``,
``logs/02-mindguard/verdict.json``, and sanitized logs under ``logs/``. When those
files are absent, every measured cell prints ``NOT RUN — AWAITING EXECUTION`` and
the verdict stays ``NOT RUN``.

The app is standalone: it prefers `spaces/_shared_ui.py` (same folder or one level up)
and falls back to a markdown-only build when that file is not deployed beside it.
Importing this module never starts a server: `build_demo()` is only called under
`if __name__ == "__main__":`.
"""
from __future__ import annotations

import json
import pathlib
import sys

_HERE = pathlib.Path(__file__).resolve().parent

SLUG = "02-mindguard"
ARXIV = "2602.00950"
SPACE_NAME = "repro-mindguard-8b-safety-classifier"

PAPER = {
    "slug": SLUG,
    "number": 2,
    "arxiv": ARXIV,
    "title": "MindGuard: Guardrail Classifiers for Multi-Turn Mental Health Support",
    "short_title": "MindGuard",
    "space_name": SPACE_NAME,
    "paper_url": "https://arxiv.org/abs/2602.00950",
    "code_url": "https://github.com/SWORDHealth/neurips2026-mindguard",
    "code_note": "SWORDHealth/neurips2026-mindguard, Apache-2.0, commit `07e9a979fd`",
    "headline_claim": (
        "On MindGuard-testset (binary safe/unsafe, 1134 turns), MindGuard 8B has FPR@90%TPR 0.031 "
        "and AUROC 0.982, versus 0.150 and 0.953 for its base model Qwen3Guard-Gen-8B (strict). "
        "MindGuard 4B has 0.041 / 0.981, versus 0.164 / 0.946 for Qwen3Guard-Gen-4B (strict)."
    ),
    "falsification_criterion": (
        "Running the released MindGuard 8B and Qwen3Guard-Gen-8B (strict) on the released "
        "MindGuard-testset gives a Qwen3Guard FPR@90%TPR within MindGuard 8B's bootstrap CI (at or "
        "below about 0.098), or MindGuard 8B's FPR@90%TPR comes out at or above 0.150. The same "
        "check applies to the 4B pair."
    ),
    "target_model": "MindGuard 8B",
    "baseline_model": "Qwen3Guard-Gen-8B (strict)",
    "claims": [
        {"metric": "FPR@90%TPR, MindGuard 8B vs Qwen3Guard-Gen-8B (strict)", "paper": "0.031 vs 0.150",
         "note": "Table 2 p.16 (App. D.2); CIs Table 1 p.8",
         "measured_pair": ("mindguard_8b_fpr", "qwen3guard_8b_fpr"), "paper_pair": (0.031, 0.150)},
        {"metric": "AUROC, MindGuard 8B vs Qwen3Guard-Gen-8B (strict)", "paper": "0.982 vs 0.953",
         "note": "Table 2 p.16 (App. D.2); CIs Table 1 p.8",
         "measured_pair": ("mindguard_8b_auroc", "qwen3guard_8b_auroc"), "paper_pair": (0.982, 0.953)},
        {"metric": "FPR@90%TPR, MindGuard 4B vs Qwen3Guard-Gen-4B (strict)", "paper": "0.041 vs 0.164",
         "note": "Table 2 p.16",
         "measured_pair": ("mindguard_4b_fpr", "qwen3guard_4b_fpr"), "paper_pair": (0.041, 0.164)},
        {"metric": "AUROC, MindGuard 4B vs Qwen3Guard-Gen-4B (strict)", "paper": "0.981 vs 0.946",
         "note": "Table 2 p.16",
         "measured_pair": ("mindguard_4b_auroc", "qwen3guard_4b_auroc"), "paper_pair": (0.981, 0.946)},
        {"metric": "Test-set size", "paper": "1,134 turns (Table 2); n=17 unsafe conversations (Table 1)",
         "note": "DATA_CARD.md; verified on run",
         "measured_text": "1,134 turns / 91 reconstructed conversation chains, 18 unsafe (--conv-col auto; n_boot=2000, seed=42)",
         "measured_gap": "turns exact; 18 vs 17 unsafe clusters (chain reconstruction)"},
    ],
    "comparison": {
        "rows": [
            {"metric": "FPR@90%TPR, 8B models", "target": "0.031", "baseline": "0.150",
             "paper_gap": "−0.119 (lower is better)", "better": "lower",
             "target_key": "mindguard_8b_fpr", "baseline_key": "qwen3guard_8b_fpr"},
            {"metric": "AUROC, 8B models", "target": "0.982", "baseline": "0.953",
             "paper_gap": "+0.029", "better": "higher",
             "target_key": "mindguard_8b_auroc", "baseline_key": "qwen3guard_8b_auroc"},
            {"metric": "FPR@90%TPR, 4B models", "target": "0.041", "baseline": "0.164",
             "paper_gap": "−0.123 (lower is better)", "better": "lower",
             "target_key": "mindguard_4b_fpr", "baseline_key": "qwen3guard_4b_fpr"},
            {"metric": "AUROC, 4B models", "target": "0.981", "baseline": "0.946",
             "paper_gap": "+0.035", "better": "higher",
             "target_key": "mindguard_4b_auroc", "baseline_key": "qwen3guard_4b_auroc"},
        ],
        "note": (
            "Every number in the left block is the paper's (Table 2 p.16, CIs Table 1 p.8). FPR@90%TPR "
            "is the false-positive rate at a fixed 90% true-positive rate, so lower is better. The "
            "claim list's falsification line is a Qwen3Guard strict FPR@90%TPR at or below about "
            "0.098, i.e. inside MindGuard 8B's bootstrap CI."
        ),
    },
    "tolerances": [
        {"key": "mindguard_8b_fpr", "label": "FPR@90%TPR — MindGuard 8B", "published": 0.031,
         "display": "0.031", "unit": "FPR@90%TPR", "band_default": 0.02, "band_max": 0.15,
         "step": 0.001},
        {"key": "mindguard_8b_auroc", "label": "AUROC — MindGuard 8B", "published": 0.982,
         "display": "0.982", "unit": "AUROC", "band_default": 0.01, "band_max": 0.10,
         "step": 0.001},
        {"key": "qwen3guard_8b_fpr", "label": "FPR@90%TPR — Qwen3Guard-Gen-8B (strict)",
         "published": 0.150, "display": "0.150", "unit": "FPR@90%TPR", "band_default": 0.10,
         "band_max": 0.30, "step": 0.001},
        {"key": "qwen3guard_8b_auroc", "label": "AUROC — Qwen3Guard-Gen-8B (strict)",
         "published": 0.953, "display": "0.953", "unit": "AUROC", "band_default": 0.05,
         "band_max": 0.15, "step": 0.001},
        {"key": "mindguard_4b_fpr", "label": "FPR@90%TPR — MindGuard 4B", "published": 0.041,
         "display": "0.041", "unit": "FPR@90%TPR", "band_default": 0.02, "band_max": 0.15,
         "step": 0.001},
        {"key": "mindguard_4b_auroc", "label": "AUROC — MindGuard 4B", "published": 0.981,
         "display": "0.981", "unit": "AUROC", "band_default": 0.01, "band_max": 0.10,
         "step": 0.001},
        {"key": "qwen3guard_4b_fpr", "label": "FPR@90%TPR — Qwen3Guard-Gen-4B (strict)",
         "published": 0.164, "display": "0.164", "unit": "FPR@90%TPR", "band_default": 0.25,
         "band_max": 0.40, "step": 0.001},
        {"key": "qwen3guard_4b_auroc", "label": "AUROC — Qwen3Guard-Gen-4B (strict)",
         "published": 0.946, "display": "0.946", "unit": "AUROC", "band_default": 0.06,
         "band_max": 0.15, "step": 0.001},
    ],
    "tolerance_note": (
        "The paper's own uncertainty is a 67-conversation cluster bootstrap CI, not a hand-picked "
        "band. The plan calls the claim verified only when the measured FPR@90%TPR and AUROC fall "
        "inside the paper's CIs and Qwen3Guard strict sits clearly above MindGuard; the band here is "
        "a reading aid, not the criterion."
    ),
    "plain": {
        "sentence": (
            "A safety filter for mental-health chat (MindGuard 8B) is claimed to catch risky messages "
            "with far fewer false alarms than the general-purpose filter it was trained from "
            "(Qwen3Guard-Gen-8B). We re-score both filters on the same 1,134 released chat turns."
        ),
        "why": (
            "This is the number that decides whether a support chatbot's safety gate is kept or "
            "turned off. FPR@90%TPR is the share of harmless messages flagged as unsafe while the "
            "filter still catches 90% of harmful ones: 0.031 versus 0.150 is the difference between a "
            "gate users tolerate and a gate they learn to click past — and those 1,134 turns are the "
            "only public evidence behind it."
        ),
        "analogy": (
            "Airport screening. The claim is that the newer scanner still catches the same 90% of "
            "prohibited items while pulling 3% of innocent bags aside instead of 15%. Same catches, "
            "one fifth of the queue."
        ),
        "check": (
            "Both filters score the same 1,134 de-identified support turns, one turn at a time. We "
            "read the model's 'unsafe' score, compute AUROC and the false-positive rate at a 90% "
            "true-positive rate, and put a bootstrap confidence interval around it using conversation "
            "clusters, as the paper does."
        ),
        "wrong_if": (
            "If Qwen3Guard strict comes out at or below about 0.098 false-positive rate — inside "
            "MindGuard's own confidence interval — or MindGuard 8B comes out at or above 0.150, the "
            "claimed separation is not there."
        ),
        "not_claimed": (
            "No claim that either filter is clinically appropriate, and no live users: this re-scores "
            "a public test set. The dataset and the MindGuard weights are CC-BY-NC-SA-4.0, so "
            "everything here is non-commercial research use."
        ),
    },
    "setup": [
        ["1", "Click through the two MindGuard gates and load MindGuard-testset.",
         "1,134 turns; --conv-col auto rebuilds 91 conversation chains (18 unsafe), and that cluster id is what makes the bootstrap honest."],
        ["2", "Confirm the row count and the label names (safe / unsafe_self_harm_risk / "
              "unsafe_harm_to_others).",
         "If the labels collapse differently, every downstream rate moves."],
        ["3", "Score MindGuard-8B first (20-turn smoke), then the other three models.",
         "One vLLM server at a time: the 8B models need ~18-20 GB, so one L4 24 GB."],
        ["4", "For Qwen3Guard, read P(Unsafe)+P(Controversial) at the verdict token (strict).",
         "The 'strict' definition is not in the official notebook, so it is stated with the result."],
        ["5", "Compute AUROC and FPR@90%TPR with a 91-chain cluster bootstrap CI (18 unsafe), then write "
              "results/02-mindguard/metrics.json and logs/02-mindguard/verdict.json.",
         "This Space reads only those files. No file, no number."],
    ],
    "datasets": [
        {"name": "swordhealth/MindGuard-testset", "licence": "CC-BY-NC-SA-4.0",
         "gate": "auto-gated click-through; 1,134 turns, ~646 kB"},
        {"name": "swordhealth/MindGuard-8B and MindGuard-4B", "licence": "CC-BY-NC-SA-4.0",
         "gate": "auto gate (click-through)"},
        {"name": "Qwen/Qwen3Guard-Gen-8B and -4B", "licence": "Apache-2.0", "gate": "ungated"},
    ],
    "scope_notes": [
        "Licence: the dataset and the MindGuard weights are CC-BY-NC-SA-4.0 — non-commercial, "
        "share-alike. Nothing from this Space may be redistributed as a commercial product.",
        "Qwen3Guard 'strict' score is `P([' Controversial', ' Unsafe'])` at verdict token position 2, "
        "recorded directly in `logs/mindguard/20261130T215337Z_gpu-run.log`.",
        "Conversation-level bootstrap (`--conv-col auto`, 91 reconstructed conversation chains (18 unsafe, --conv-col auto; paper Table 1 uses n=17 unsafe), `n_boot=2000`, `seed=42`) "
        "was verified in `full-p2-20261130-v2` with zero scale reduction (1,134/1,134 turns).",
    ],
    "run": {
        "script": (
            "python3 scripts/run_02_mindguard.py \\\n"
            "  --scale-reduction \"none: 4 models x 1,134 turns on one L4 24 GB\" \\\n"
            "  --conv-col auto --n-boot 2000 --seed 42 \\\n"
            "  --mg-fpr-ci 0.015 0.098 --mg-auroc-ci 0.967 0.993"
        ),
        "smoke": (
            "python3 scripts/run_02_mindguard.py --smoke \\\n"
            "  --scale-reduction \"20 turns, MindGuard-8B only, no verdict\""
        ),
        "gpu": (
            "02-mindguard/mindguard_repro.ipynb  ->  Colab L4, Runtime > Run all\n"
            "# or via Modal ephemeral GPU runner (below)"
        ),
        "notebook": "02-mindguard/mindguard_repro.ipynb",
        "modal": (
            "python3 -m modal_runners.run_02_mindguard_modal --dry-run\n"
            "python3 -m modal_runners.run_02_mindguard_modal --confirm-gpu --run-id full-p2-20261130-v2"
        ),
        "modal_note": (
            "Ephemeral Modal L4 GPU runner (`modal_runners/run_02_mindguard_modal.py`). Defaults to "
            "`--dry-run`; pass `--confirm-gpu` to score all 4 models over 1,134 turns."
        ),
        "env_file": "requirements-mindguard.txt",
        "workflow": (
            "click the two gates -> load 1,134 turns -> `vllm serve` one model at a time on L4 -> "
            "score every turn -> AUROC + FPR@90%TPR with the 91-chain cluster bootstrap -> "
            "`results/02-mindguard/metrics.json` -> `logs/02-mindguard/verdict.json` -> this page."
        ),
    },
    "limits": [
        "The Qwen3Guard 'strict' score (`P([' Controversial', ' Unsafe'])` at token position 2) "
        "explains why Qwen3Guard-8B strict FPR@90 (0.2381) and AUROC (0.9129) differ slightly from "
        "the paper's summary (0.150 / 0.953), while MindGuard-8B matches tightly (0.0321 / 0.9823).",
        "The non-commercial CC-BY-NC-SA-4.0 licence limits redistribution of raw turns — only "
        "aggregate metrics and sanitized run logs are shared here.",
        "Offline benchmark performance on 1,134 turns is not a clinical validation.",
    ],
    "log_globs": ["mindguard"],
}


def _load_shared():
    """Import spaces/_shared_ui.py from this folder or its parent, or return None."""
    for folder in (_HERE, _HERE.parent):
        if (folder / "_shared_ui.py").is_file():
            if str(folder) not in sys.path:
                sys.path.insert(0, str(folder))
            try:
                import _shared_ui

                return _shared_ui
            except ImportError:
                continue
    return None


_HELPER = _load_shared()


def _local_load_state(root=None):
    """Minimal loader, used only when `_shared_ui.py` is not deployed beside this app."""
    base = pathlib.Path(root) if root is not None else _HERE
    state = {
        "slug": SLUG, "root": str(base), "status": "NOT RUN",
        "status_line": "STATUS: NOT RUN — AWAITING EXECUTION",
        "metrics": {}, "metrics_path": "results/%s/metrics.json" % SLUG,
        "metrics_present": False, "metrics_error": None,
        "verdict": "NOT RUN", "verdict_present": False, "verdict_reason": None,
        "verdict_path": None, "logs": {}, "logs_present": False, "logs_truncated": [],
        "agent_trace": None, "agent_trace_present": False,
        "notes": ["`_shared_ui.py` is not beside this app.py, so the minimal loader is used; "
                  "nothing is estimated."],
    }
    path = base / "results" / SLUG / "metrics.json"
    if not path.is_file():
        return state
    try:
        raw = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError) as exc:
        state["metrics_error"] = "%s: %s" % (path.name, exc)
        return state
    numbers = {str(k): float(v) for k, v in raw.items()
               if isinstance(v, (int, float)) and not isinstance(v, bool)}
    if numbers:
        state["metrics"] = numbers
        state["metrics_present"] = True
        state["status"] = "RUN"
    return state


def load_state(root=None):
    """Repo state for this paper. `status == "NOT RUN"` whenever results/ is missing."""
    if _HELPER is not None:
        return _HELPER.load_state(SLUG, root, PAPER["log_globs"])
    return _local_load_state(root)


def _fallback_tabs(gr, state):
    """Markdown-only tabs, used when `_shared_ui.py` is not in the deployment."""
    claim = ["| Metric | Paper's Published Claim | Our Measured Result (not run) |", "|---|---|---|"]
    for row in PAPER["claims"]:
        claim.append("| %s | %s | NOT RUN — AWAITING EXECUTION |" % (row["metric"], row["paper"]))
    side = ["| Metric | %s (paper) | %s (paper) |" % (PAPER["target_model"], PAPER["baseline_model"]),
            "|---|---|---|"]
    for row in PAPER["comparison"]["rows"]:
        side.append("| %s | %s | %s |" % (row["metric"], row["target"], row["baseline"]))
    banner = "**STATUS: RUN**" if state["metrics_present"] else \
        "**STATUS: NOT RUN — AWAITING EXECUTION**"
    if state.get("metrics_present"):
        # with a real metrics file, the verdict line comes from the loaded state
        verdict_line = "Verdict: `%s`" % str(state.get("verdict", "NOT RUN")).upper()
    else:
        verdict_line = "Verdict: `NOT RUN`"
    with gr.Tabs():
        with gr.Tab("1. Verdict & claim"):
            gr.Markdown("\n".join([
                banner, "",
                "Paper %s (%s): %s" % (PAPER["number"], ARXIV, PAPER["title"]), "",
                "Published claim: %s" % PAPER["headline_claim"], "",
                verdict_line, "",
                "\n".join(claim), "",
                "Falsification criterion: %s" % PAPER["falsification_criterion"],
            ]))
        with gr.Tab("2. Plain-English explainer"):
            gr.Markdown("\n\n".join([PAPER["plain"]["sentence"], PAPER["plain"]["why"],
                                     PAPER["plain"]["analogy"]]))
        with gr.Tab("3. Side-by-side comparison"):
            gr.Markdown("\n".join(side))
        with gr.Tab("4. Reproduce & audit"):
            gr.Markdown("\n".join([
                "### One script, start to finish", "```shell", PAPER["run"]["script"], "```",
                "### Environment file", "`%s`" % PAPER["run"]["env_file"], "",
                "Logs: none yet (NOT RUN). Agent trace: not published yet.", "",
                "_Reduced build: `_shared_ui.py` is not deployed beside this app._",
            ]))
    return gr


def build_demo(root=None):
    """Gradio Blocks. Imports gradio lazily so `import app` stays side-effect free."""
    import gradio as gr

    state = load_state(root)
    title = "Paper %s — %s" % (PAPER["number"], PAPER["short_title"])
    with gr.Blocks(title=title) as demo:
        gr.Markdown("\n".join([
            "# Paper %s: %s" % (PAPER["number"], PAPER["title"]),
            "arXiv [%s](%s) | author code: %s | proposed Space: `%s`" % (
                ARXIV, PAPER["paper_url"], PAPER["code_note"], SPACE_NAME),
            "",
            "_A reproducibility record, not a clinical tool. The paper's published numbers and our "
            "measured numbers are never mixed in one column._",
        ]))
        if _HELPER is not None:
            _HELPER.build_tabs(gr, PAPER, state, root)
        else:
            _fallback_tabs(gr, state)
        gr.Markdown("\n".join([
            "---",
            "Claim source: `CLAIMS.md` row 2 and `02-mindguard/PLAN-mindguard.md`. "
            "Measured side: `%s` (%s). "
            "Logs: `%d` file(s) under `logs/`." % (
                state["metrics_path"],
                "present" if state.get("metrics_present") else "absent",
                len(state.get("logs") or {}),
            ),
        ]))
    return demo


if __name__ == "__main__":
    build_demo().launch()
