#!/usr/bin/env python3
"""Build isolated UN R155 test copies of existing T-xxx Threat Register pages."""
from __future__ import annotations

import argparse
import html
import json
import re
import shutil
import subprocess
import sys
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any


def e(value: Any) -> str:
    return html.escape(str(value if value is not None else ""), quote=True)


def load_json(path: Path) -> dict[str, Any]:
    if not path.is_file():
        raise FileNotFoundError(f"Input file not found: {path}")
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise ValueError(
            f"Invalid JSON in {path}: line {exc.lineno}, column {exc.colno}: {exc.msg}"
        ) from exc
    if not isinstance(data, dict):
        raise ValueError(f"Expected JSON object in {path}")
    return data


def args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Build isolated UN R155 test copies of T-xxx pages"
    )
    parser.add_argument("--project-root", type=Path, default=Path("."))
    parser.add_argument("--regulatory-root", type=Path, default=Path("regulatory/r155"))
    parser.add_argument("--threat-register", type=Path, default=Path("data/threats_register.json"))
    parser.add_argument("--source-pages", type=Path, default=Path("site/threats"))
    parser.add_argument("--output", type=Path, default=Path("site/r155"))
    parser.add_argument(
        "--validator",
        type=Path,
        default=Path("regulatory/r155/validate_r155.py"),
    )
    parser.add_argument(
        "--skip-validation",
        action="store_true",
        help="Skip validate_r155.py (not recommended)",
    )
    return parser.parse_args()


def resolve(root: Path, value: Path) -> Path:
    return value if value.is_absolute() else root / value


def node_title(node: dict[str, Any]) -> str:
    return str(node.get("label") or node.get("title") or node.get("description") or "")


def node_kind(node: dict[str, Any]) -> str:
    value = str(node.get("type") or node.get("node_type") or "node")
    return value.replace("_", " ")


def source_link(source: dict[str, Any]) -> str:
    label = source.get("document_reference") or source.get("source_id") or "Official source"
    url = str(source.get("url") or "").strip()
    if url.startswith("https://") or url.startswith("http://"):
        return f'<a href="{e(url)}" target="_blank" rel="noopener noreferrer">{e(label)} ↗</a>'
    return e(label)


def mapping_strength(mapping: dict[str, Any]) -> str:
    return str(mapping.get("mapping_strength") or mapping.get("relationship") or "candidate")


def render_mitigation(node: dict[str, Any]) -> str:
    return (
        '<div class="r155-mitigation">'
        '<div class="r155-node-line">'
        f'<span class="r155-ref">{e(node.get("part", "-"))} / {e(node.get("table", "-"))} / {e(node.get("reference", "-"))}</span>'
        f'<span class="r155-kind">{e(node_kind(node))}</span>'
        '</div>'
        f'<div class="r155-node-title">{e(node_title(node))}</div>'
        '</div>'
    )


def render_mapping(
    mapping: dict[str, Any],
    nodes: dict[str, dict[str, Any]],
    versions: list[dict[str, Any]],
) -> str:
    node_id = str(mapping.get("regulatory_node_id") or "")
    node = nodes[node_id]
    mitigation_ids: list[str] = []
    for value in list(mapping.get("mitigation_nodes") or []) + list(node.get("related_mitigations") or []):
        if value in nodes and value not in mitigation_ids:
            mitigation_ids.append(value)
    affected_versions = [
        version
        for version in versions
        if node_id in (version.get("affected_nodes") or [])
        or any(mid in (version.get("affected_nodes") or []) for mid in mitigation_ids)
    ]
    version_html = "".join(
        '<li>'
        f'<strong>{e(version.get("amendment_label") or version.get("version_id"))}</strong>'
        f' · entry into force {e(version.get("entry_into_force") or "-")}'
        f' · legal basis {e(version.get("legal_basis_reference") or "-")}'
        '</li>'
        for version in affected_versions
    ) or '<li>No node-specific amendment recorded in versions.json; base/version basis applies.</li>'
    mitigations = "".join(render_mitigation(nodes[mid]) for mid in mitigation_ids)
    if not mitigations:
        mitigations = '<p class="muted small">No corresponding mitigation node recorded.</p>'
    status = str(mapping.get("status") or "review").lower()
    score = mapping.get("score", mapping.get("relevance_score"))
    score_text = f"{float(score):.2f}" if isinstance(score, (int, float)) else "-"
    terms = "".join(f'<span class="r155-term">{e(term)}</span>' for term in mapping.get("matched_terms", []))
    return f'''
<article class="r155-mapping" data-status="{e(status)}">
  <div class="r155-mapping-head">
    <div>
      <span class="r155-status {e(status)}">{e(status)}</span>
      <span class="r155-strength">{e(mapping_strength(mapping))}</span>
    </div>
    <div class="r155-score">Mapping score <strong>{e(score_text)}</strong></div>
  </div>
  <div class="r155-node-line">
    <span class="r155-ref">Annex {e(node.get("annex", "5"))} · Part {e(node.get("part", "-"))} · Table {e(node.get("table", "-"))} · Ref {e(node.get("reference", "-"))}</span>
    <span class="r155-kind">{e(node_kind(node))}</span>
  </div>
  <h3>{e(node_title(node))}</h3>
  <p class="small"><strong>Category:</strong> {e(node.get("category_reference") or "-")} · {e(node.get("category_title") or "-")}</p>
  <p class="small"><strong>NCRC rationale:</strong> {e(mapping.get("rationale") or "-")}</p>
  <div class="r155-terms">{terms}</div>
  <details>
    <summary>Corresponding mitigations ({len(mitigation_ids)})</summary>
    <div class="r155-mitigations">{mitigations}</div>
  </details>
  <details>
    <summary>Version and amendment traceability</summary>
    <ul class="small">{version_html}</ul>
  </details>
  <div class="r155-id small">Mapping: {e(mapping.get("mapping_id"))} · Node: {e(node_id)}</div>
</article>
'''


def render_r155_section(
    threat_id: str,
    threat_mappings: list[dict[str, Any]],
    nodes: dict[str, dict[str, Any]],
    versions: list[dict[str, Any]],
    sources: list[dict[str, Any]],
) -> str:
    status_counts = Counter(str(item.get("status") or "review") for item in threat_mappings)
    body = "".join(render_mapping(item, nodes, versions) for item in threat_mappings)
    if not body:
        body = (
            '<div class="r155-empty"><strong>No R155 mapping candidates</strong>'
            '<p>No candidate relationship between this threat and the current Annex 5 mapping set was generated.</p></div>'
        )
    source_items = "".join(
        '<li>'
        f'{source_link(source)}'
        f' · {e(source.get("source_status") or source.get("source_type") or "-")}'
        f' · {e(source.get("legal_status") or "-")}'
        + (
            f' · authentic legal reference: {e(source.get("authentic_legal_reference") or source.get("legal_binding_reference"))}'
            if source.get("authentic_legal_reference") or source.get("legal_binding_reference")
            else ""
        )
        + '</li>'
        for source in sources
    )
    return f'''
<section class="card r155-panel" id="r155">
  <div class="r155-heading">
    <div>
      <p class="section-kicker">Regulatory traceability test</p>
      <h2>UN Regulation No. 155</h2>
      <p class="muted small">Experimental NCRC mapping of {e(threat_id)} to UN R155 Annex 5. A mapping is analytical traceability, not a determination of compliance, non-compliance or legal effect.</p>
    </div>
    <span class="r155-test-badge">TEST COPY</span>
  </div>
  <div class="r155-audit-relevance">
    <div class="r155-audit-kicker">Audit relevance</div>
    <p>UN R155 Annex 5 Parts A, B and C are intended to be considered in risk assessment and mitigation. The mappings below identify Annex 5 areas potentially relevant to this Threat Register entry. They do not establish compliance or non-compliance.</p>
    <div class="r155-audit-question">
      <span>Assessment question</span>
      <strong>Is there sufficient evidence that the relevant threat scenarios and corresponding mitigations were considered in the applicable risk assessment?</strong>
    </div>
  </div>
  <div class="r155-summary">
    <div><strong>{len(threat_mappings)}</strong><span>Mappings</span></div>
    <div><strong>{status_counts.get("review", 0)}</strong><span>Review</span></div>
    <div><strong>{status_counts.get("accepted", 0)}</strong><span>Accepted</span></div>
    <div><strong>{len({m for item in threat_mappings for m in item.get("mitigation_nodes", [])})}</strong><span>Mitigation refs</span></div>
  </div>
  {body}
  <details class="r155-sources">
    <summary>Regulatory sources and legal status</summary>
    <ul class="small">{source_items}</ul>
  </details>
</section>
'''


R155_CSS = r'''
<style id="r155-test-style">
.r155-panel{border-top:4px solid #325d88;scroll-margin-top:18px}.r155-audit-relevance{margin:16px 0;padding:15px 16px;background:color-mix(in srgb,var(--accent) 6%,var(--surface-alt));border:1px solid color-mix(in srgb,var(--accent) 22%,var(--line));border-left:4px solid var(--accent);border-radius:6px}.r155-audit-relevance p{margin:6px 0 12px}.r155-audit-kicker{color:var(--accent);font-size:.78rem;font-weight:800;text-transform:uppercase;letter-spacing:.06em}.r155-audit-question{padding:11px 12px;background:var(--bg);border:1px solid var(--line);border-radius:5px}.r155-audit-question span{display:block;color:var(--muted);font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;margin-bottom:4px}.r155-audit-question strong{font-size:.9rem}.r155-heading{display:flex;justify-content:space-between;gap:20px;align-items:flex-start}.r155-test-badge{padding:5px 9px;border:1px solid #b37a20;border-radius:5px;color:#b37a20;font-size:.72rem;font-weight:800;letter-spacing:.08em}.r155-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:8px;margin:16px 0}.r155-summary>div{padding:11px;background:var(--surface-alt);border:1px solid var(--line);border-radius:5px}.r155-summary strong{display:block;font-size:1.25rem;color:var(--accent)}.r155-summary span{font-size:.72rem;color:var(--muted)}.r155-mapping{border:1px solid var(--line);border-left:4px solid #b37a20;border-radius:6px;padding:14px;margin:12px 0;background:var(--surface-alt)}.r155-mapping[data-status="accepted"]{border-left-color:#2f7d59}.r155-mapping[data-status="rejected"]{border-left-color:#8c4a4a}.r155-mapping-head,.r155-node-line{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}.r155-status,.r155-strength,.r155-ref,.r155-kind,.r155-term{display:inline-block;padding:2px 7px;border-radius:10px;font-size:.7rem}.r155-status{border:1px solid currentColor;text-transform:uppercase;font-weight:800;color:#b37a20}.r155-status.accepted{color:#2f7d59}.r155-strength,.r155-kind,.r155-term{background:var(--bg);border:1px solid var(--line);color:var(--muted)}.r155-ref{font-family:monospace;background:color-mix(in srgb,var(--accent) 10%,transparent);color:var(--accent)}.r155-score,.r155-id{color:var(--muted)}.r155-mapping h3{margin:10px 0 6px}.r155-terms{display:flex;gap:5px;flex-wrap:wrap;margin:8px 0}.r155-mitigation{padding:10px 0;border-bottom:1px solid var(--line)}.r155-mitigation:last-child{border-bottom:0}.r155-node-title{margin-top:5px}.r155-empty{padding:18px;background:var(--surface-alt);border:1px solid var(--line);border-radius:6px}.r155-sources{margin-top:16px;padding-top:12px;border-top:1px solid var(--line)}.r155-regulatory-link{float:right;display:inline-flex;align-items:center;gap:7px;margin-left:auto;padding:9px 12px;border:1px solid var(--accent);border-radius:6px;background:color-mix(in srgb,var(--accent) 7%,var(--surface));color:var(--accent);font-size:.78rem;font-weight:800;text-decoration:none}.r155-regulatory-link:hover{background:color-mix(in srgb,var(--accent) 13%,var(--surface));text-decoration:none}.r155-regulatory-count{display:inline-flex;min-width:22px;height:22px;align-items:center;justify-content:center;border-radius:11px;background:var(--accent);color:var(--surface);font-size:.7rem}@media(max-width:700px){.r155-heading{flex-direction:column}.r155-regulatory-link{float:none;margin:10px 0 0}}
</style>
'''


def adjust_copy_links(page: str) -> str:
    # In the copied page, ../index.html intentionally points to the R155 test index.
    # Other dashboard navigation must still point to the production site root.
    for name in ("github", "cves", "papers", "signals", "incidents", "about", "statistics"):
        page = page.replace(f'href="../{name}.html"', f'href="../../{name}.html"')
    page = page.replace(
        '<a class="site-brand" href="../index.html">',
        '<a class="site-brand" href="../../index.html">',
    )
    return page


def add_regulatory_hero_link(page: str, mapping_count: int) -> str:
    link = (
        f'<a class="r155-regulatory-link" href="#r155" title="Jump to UN R155 regulatory traceability">'
        f'<span>Regulatory</span>'
        f'<span class="r155-regulatory-count">{mapping_count}</span>'
        f'<span aria-hidden="true">&#8250;</span></a>'
    )
    if 'class="r155-regulatory-link"' in page:
        return re.sub(r'<a class="r155-regulatory-link".*?</a>', link, page, count=1, flags=re.S)
    # The copied production hero closes immediately before the first Assessment card.
    marker = '</div><div class="card"><h2>Assessment</h2>'
    if marker in page:
        return page.replace('</div><div class="card"><h2>Assessment</h2>', link + '</div><div class="card"><h2>Assessment</h2>', 1)
    # Fallback: add immediately before the first hero closing tag.
    m = re.search(r'(<div class="hero".*?)(</div>)', page, flags=re.S)
    if not m:
        raise ValueError("Could not locate threat hero for Regulatory link")
    return page[:m.start()] + m.group(1) + link + m.group(2) + page[m.end():]


def inject(page: str, section: str) -> str:
    if 'id="r155"' in page:
        page = re.sub(r'<section class="card r155-panel" id="r155">.*?</section>', section, page, flags=re.S)
    else:
        marker = '<div class="nav">'
        if marker in page:
            page = page.replace(marker, section + marker, 1)
        elif "</main>" in page:
            page = page.replace("</main>", section + "</main>", 1)
        else:
            raise ValueError("Could not find insertion point in copied threat page")
    if 'id="r155-test-style"' not in page:
        page = page.replace("</head>", R155_CSS + "</head>", 1)
    return page


def build_index(threats: list[dict[str, Any]], by_threat: dict[str, list[dict[str, Any]]]) -> str:
    rows = []
    for threat in threats:
        tid = str(threat.get("id") or "")
        mappings = by_threat.get(tid, [])
        counts = Counter(str(x.get("status") or "review") for x in mappings)
        rows.append(
            '<tr>'
            f'<td><a href="threats/{e(tid)}.html">{e(tid)}</a></td>'
            f'<td>{e(threat.get("title") or "")}</td>'
            f'<td>{len(mappings)}</td><td>{counts.get("review",0)}</td><td>{counts.get("accepted",0)}</td>'
            '</tr>'
        )
    return f'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>UN R155 Threat Register Test</title><style>
:root{{--bg:#eef1f5;--surface:#fff;--ink:#1b2430;--muted:#5d6b7c;--line:#d5dce5;--accent:#1f4e79}}@media(prefers-color-scheme:dark){{:root{{--bg:#12171e;--surface:#1a212b;--ink:#e6ebf1;--muted:#93a1b3;--line:#2c3644;--accent:#7db4e6}}}}*{{box-sizing:border-box}}body{{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 "Segoe UI",system-ui,sans-serif}}main{{max-width:1200px;margin:auto;padding:24px}}.card{{background:var(--surface);border:1px solid var(--line);border-radius:7px;padding:20px;margin-bottom:18px}}a{{color:var(--accent);text-decoration:none}}.muted{{color:var(--muted)}}table{{width:100%;border-collapse:collapse}}th,td{{text-align:left;padding:9px;border-bottom:1px solid var(--line)}}.notice{{border-left:4px solid #b37a20}}input{{width:100%;padding:9px;border:1px solid var(--line);border-radius:5px;background:var(--bg);color:var(--ink);margin-bottom:12px}}
</style></head><body><main><p><a href="../index.html">← Production Threat Register</a></p><section class="card notice"><h1>UN R155 Threat Register Test</h1><p class="muted">Isolated test copies of all T-xxx pages. Production pages are not modified. Regulatory mappings are analytical review material and do not constitute compliance determinations.</p></section><section class="card"><input id="q" type="search" placeholder="Filter threat ID or title"><table><thead><tr><th>ID</th><th>Threat</th><th>Mappings</th><th>Review</th><th>Accepted</th></tr></thead><tbody id="rows">{''.join(rows)}</tbody></table></section><script>const q=document.getElementById('q'),rows=[...document.querySelectorAll('#rows tr')];q.addEventListener('input',()=>{{const v=q.value.toLowerCase();rows.forEach(r=>r.style.display=r.textContent.toLowerCase().includes(v)?'':'none')}});</script></main></body></html>'''


def main() -> int:
    cfg = args()
    root = cfg.project_root.resolve()
    reg_root = resolve(root, cfg.regulatory_root)
    threat_register = resolve(root, cfg.threat_register)
    source_pages = resolve(root, cfg.source_pages)
    output = resolve(root, cfg.output)
    validator = resolve(root, cfg.validator)

    if not cfg.skip_validation:
        if not validator.is_file():
            raise FileNotFoundError(f"Validator not found: {validator}")
        result = subprocess.run(
            [sys.executable, str(validator), str(reg_root), "--threat-register", str(threat_register)],
            cwd=root,
        )
        if result.returncode != 0:
            raise RuntimeError("R155 validation failed; test pages were not generated")

    register = load_json(threat_register)
    annex = load_json(reg_root / "annex5.json")
    mapping_data = load_json(reg_root / "r155_threat_mappings.json")
    version_data = load_json(reg_root / "versions.json")
    source_data = load_json(reg_root / "sources.json")

    threats = [x for x in register.get("threats", []) if isinstance(x, dict) and x.get("id")]
    nodes = {str(x["id"]): x for x in annex.get("nodes", []) if isinstance(x, dict) and x.get("id")}
    versions = [x for x in version_data.get("versions", []) if isinstance(x, dict)]
    sources = [x for x in source_data.get("sources", []) if isinstance(x, dict)]
    by_threat: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for mapping in mapping_data.get("mappings", []):
        if isinstance(mapping, dict):
            by_threat[str(mapping.get("threat_id") or "")].append(mapping)
    for values in by_threat.values():
        values.sort(key=lambda x: float(x.get("score", x.get("relevance_score", 0)) or 0), reverse=True)

    staging = output.with_name(output.name + ".tmp")
    if staging.exists():
        shutil.rmtree(staging)
    (staging / "threats").mkdir(parents=True)

    written = 0
    for threat in threats:
        tid = str(threat["id"])
        source = source_pages / f"{tid}.html"
        if not source.is_file():
            raise FileNotFoundError(f"Production threat page not found: {source}")
        page = adjust_copy_links(source.read_text(encoding="utf-8"))
        threat_r155_mappings = by_threat.get(tid, [])
        page = add_regulatory_hero_link(page, len(threat_r155_mappings))
        section = render_r155_section(tid, threat_r155_mappings, nodes, versions, sources)
        page = inject(page, section)
        (staging / "threats" / f"{tid}.html").write_text(page, encoding="utf-8")
        written += 1

    (staging / "index.html").write_text(build_index(threats, by_threat), encoding="utf-8")
    if output.exists():
        shutil.rmtree(output)
    staging.rename(output)
    print(f"Wrote {output}/index.html and {written} R155 test threat pages")
    print(f"Mappings rendered: {sum(len(v) for v in by_threat.values())}")
    print("Production site/threats pages were not modified")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (FileNotFoundError, ValueError, RuntimeError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        raise SystemExit(2)
