#!/usr/bin/env python3
"""Build V2.2 isolated UN R155 traceability 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")


# V2.2 protected RDW baseline. Kept separate from analytical candidates.
RDW_BASELINE = {
    "T-058": ("4.3.1", "Vehicle-related backend servers", "direct", "Vehicle-related backend services are directly covered by the Annex 5 high-level area for vehicle-related back-end servers."),
    "T-059": ("4.3.2", "Vehicle communication channels", "direct", "Vehicle communication channels are directly covered by the corresponding Annex 5 high-level area."),
    "T-060": ("4.3.3", "Vehicle update procedures and UN R156", "direct", "Vehicle software-update processes align directly with the Annex 5 high-level area for vehicle update procedures; UN R156 is retained as related regulatory context."),
    "T-061": ("4.3.4", "Unintended human actions and staff privilege abuse", "direct", "Human error, social engineering and misuse of authorized access align directly with the Annex 5 high-level area covering unintended human actions."),
    "T-062": ("4.3.5", "External connectivity and connections", "direct", "Vehicle external interfaces and connected equipment align directly with the Annex 5 high-level area for external connectivity and connections."),
    "T-063": ("4.3.6", "Vehicle data and code as attack targets", "direct", "Unauthorized access to or manipulation of vehicle data, code and credentials aligns directly with the Annex 5 high-level area covering vehicle data and code as attack targets."),
    "T-064": ("4.3.7", "Exploitable vulnerabilities and insufficient protection", "direct", "Insufficiently protected vehicle systems and components align directly with the Annex 5 high-level area for exploitable vulnerabilities and insufficient protection."),
    "T-065": ("Cross-cutting", "Identity, cryptographic keys and trust services", "cross-cutting", "Covers weaknesses across the full identity, access and cryptographic trust lifecycle that could enable unauthorized access, impersonation or trusted malicious actions across many vehicles and services."),
    "T-066": ("Cross-cutting", "Perception, localization and automated-driving inputs", "cross-cutting", "Covers deliberate manipulation of sensors, positioning, maps and AI inputs that could cause automated-driving systems to misunderstand the road environment and behave unsafely."),
    "T-067": ("Cross-cutting", "Fleet, dispatch, teleoperation and mobility-control platforms", "cross-cutting", "Covers centralized operational platforms whose compromise could allow one attacker to reroute, immobilize or manipulate multiple vehicles or essential fleets simultaneously."),
    "T-068": ("Cross-cutting", "Connected road and traffic-management infrastructure", "cross-cutting", "Covers road and traffic-management systems outside the vehicle that can create unsafe traffic conditions or disrupt mobility even when individual vehicles remain secure."),
    "T-069": ("Cross-cutting", "Shared dependency / single point of failure", "cross-cutting", "Covers concentration risk where the failure or compromise of one shared supplier, platform, component or service simultaneously affects multiple fleets or mobility providers."),
}

def render_rdw_baseline(threat_id: str) -> str:
    item = RDW_BASELINE.get(threat_id)
    if not item:
        return ""
    coverage, title, relation, rationale = item
    return f"""
  <div class=\"r155-baseline\">
    <div class=\"r155-baseline-head\"><span class=\"r155-baseline-badge\">RDW BASELINE</span><span class=\"r155-strength\">{e(relation)}</span></div>
    <p class=\"small\"><strong>R155 coverage:</strong> {e(coverage)} · {e(title)}</p>
    <p class=\"small\"><strong>Mapping rationale:</strong> {e(rationale)}</p>
    <p class=\"muted small\">Protected high-level baseline. Analytical Annex 5 candidates below do not overwrite it.</p>
  </div>
"""

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)
    baseline_html = render_rdw_baseline(threat_id)
    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>
  {baseline_html}
  <div class="r155-subheading"><strong>ANALYTICAL CANDIDATES</strong><p class="muted small">Annex 5 relationships from the analytical mapping set, kept separate from the RDW baseline.</p></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>
  <div class="r155-top-return"><a href="#top">↑ TOP</a></div>
</section>
'''


R155_CSS = r'''
<style id="r155-test-style">
.hero{display:flex;flex-wrap:wrap;align-items:flex-start;gap:6px}.hero .sub,.hero h1{flex:0 0 100%}.hero .register-evidence{margin-right:0}.hero .r155-regulatory-link{margin-left:auto;align-self:flex-start}.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{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}@media(max-width:700px){.r155-heading{flex-direction:column}.r155-regulatory-link{float:none;margin:10px 0 0}}
.r155-baseline{margin:16px 0;padding:14px 16px;border:1px solid var(--line);border-left:4px solid #2f7d59;border-radius:6px;background:var(--surface-alt)}.r155-baseline-head{display:flex;justify-content:space-between;gap:10px;align-items:center}.r155-baseline-badge{padding:4px 8px;border-radius:5px;background:#2f7d59;color:#fff;font-size:.7rem;font-weight:800;letter-spacing:.07em}.r155-subheading{margin:18px 0 8px;padding-bottom:8px;border-bottom:1px solid var(--line)}.r155-subheading p{margin:4px 0 0}.r155-top-return{display:flex;justify-content:flex-end;margin-top:12px}.r155-top-return a{display:inline-flex;align-items:center;justify-content:center;padding:9px 12px;border:1px solid var(--accent);border-radius:6px;color:var(--accent);font-weight:800;text-decoration:none}.r155-top-return a:hover{background:color-mix(in srgb,var(--accent) 8%,var(--surface));text-decoration:none}
</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_top_anchor(page: str) -> str:
    """Give each copied page a stable in-page target for the TOP control."""
    if re.search(r'<body\b[^>]*\bid="top"', page, flags=re.I):
        return page
    return re.sub(r'<body\b([^>]*)>', r'<body\1 id="top">', page, count=1, flags=re.I)


def add_regulatory_hero_link(page: str, mapping_count: int) -> str:
    """
    Insert Regulatory as the final independent control in the threat hero.

    mapping_count is retained for compatibility but is not displayed.
    """
    link = (
        '<a class="r155-regulatory-link" href="#r155" '
        'title="Jump to UN R155 regulatory traceability">'
        'Regulatory'
        '</a>'
    )

    # Remove an already generated Regulatory control if present.
    page = re.sub(
        r'<a class="r155-regulatory-link".*?</a>',
        '',
        page,
        count=1,
        flags=re.S,
    )

    # Regulatory is an independent final child of the hero.
    # Do not anchor it to register-evidence because that component has
    # different structures for populated and empty evidence states.
    hero = re.search(
        r'(<div class="hero">.*?)(</div>)',
        page,
        flags=re.I | re.S,
    )

    if not hero:
        raise ValueError(
            "Could not locate threat hero for Regulatory control"
        )

    return (
        page[:hero.start()]
        + hero.group(1)
        + link
        + hero.group(2)
        + page[hero.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 V2.2</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 V2.2</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:
    expected = {f"T-{i:03d}" for i in range(58, 70)}
    if set(RDW_BASELINE) != expected:
        raise RuntimeError("RDW_BASELINE must contain exactly T-058..T-069")
    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"))
        page = add_top_anchor(page)
        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)
