#!/usr/bin/env bash
set -euo pipefail

BASE="${1:-/mnt/bigstor/www/usecases}"
TARGET="$BASE/build_about_page.py"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP="$TARGET.bak-threat-register-v06-$STAMP"

[[ -f "$TARGET" ]] || { echo "ERROR: missing $TARGET" >&2; exit 2; }
cp -a "$TARGET" "$BACKUP"

rollback() {
  echo "ERROR: patch failed; restoring $BACKUP" >&2
  cp -a "$BACKUP" "$TARGET"
}
trap rollback ERR

python3 - "$TARGET" <<'PY'
from pathlib import Path
import sys

path = Path(sys.argv[1])
text = path.read_text(encoding="utf-8")

if "def update_threat_register_section(" in text:
    print("SKIP: generator already contains the Threat Register section updater")
    raise SystemExit(0)

section = '''  <section class="card">
    <h2>The Threat Register at the centre</h2>
    <p>Different evidence sources describe different parts of the cybersecurity landscape. The Threat Register brings those sources together around the risk question. In addition to observable external evidence, threats can now be related to applicable regulatory requirements and analytical regulatory mappings. This keeps evidence, risk analysis and regulatory traceability connected without treating correlation or regulatory relevance as proof of compliance.</p>
    <div class="model" aria-label="Conceptual threat, evidence and regulatory model">
      <div class="model-register">Threat Register</div>
      <div class="model-line"></div>
      <div class="model-sources">
        <span class="model-source">CVEs</span>
        <span class="model-source">Papers</span>
        <span class="model-source">Repositories</span>
        <span class="model-source">Signals</span>
        <span class="model-source">Incidents</span>
        <span class="model-source">Assessments</span>
        <span class="model-source">Narratives</span>
      </div>
      <div class="model-line"></div>
      <div class="model-sources">
        <span class="model-source">UN R155 requirements</span>
        <span class="model-source">Annex 5 analytical candidates</span>
        <span class="model-source">Regulatory Hub</span>
      </div>
      <div class="model-line"></div>
      <div class="model-sources">
        <span class="model-source">Accepted evidence</span>
        <span class="model-source">Review candidates</span>
        <span class="model-source">Evidence gaps</span>
        <span class="model-source">Expert review</span>
      </div>
    </div>
    <p class="small muted" style="margin-top:14px;">The Regulatory Hub complements this threat-level traceability by explaining the wider regulatory frameworks, official sources, expert views and unresolved regulatory questions.</p>
  </section>
'''

function_code = "\n\ndef update_threat_register_section(about: str) -> str:\n"
function_code += "    start = '  <section class=\"card\">\\n    <h2>The Threat Register at the centre</h2>'\n"
function_code += "    end = '  <section class=\"card\">\\n    <h2>Evidence sources</h2>'\n"
function_code += "    start_pos = about.find(start)\n"
function_code += "    end_pos = about.find(end, start_pos + 1)\n"
function_code += "    if start_pos < 0 or end_pos < 0:\n"
function_code += "        raise ValueError(\"Could not locate The Threat Register at the centre section\")\n"
function_code += f"    section = {section!r}\n"
function_code += "    return about[:start_pos] + section + about[end_pos:]\n"

function_anchor = "\ndef atomic_write(path: Path, text: str) -> None:\n"
if text.count(function_anchor) != 1:
    raise SystemExit("ERROR: atomic_write anchor missing or not unique")
text = text.replace(function_anchor, function_code + function_anchor, 1)

update_anchor = "    updated = VERSION_BLOCK_RX.sub(lambda _: block, about, count=1)\n"
if text.count(update_anchor) != 1:
    raise SystemExit("ERROR: version update anchor missing or not unique")
text = text.replace(
    update_anchor,
    update_anchor + "    updated = update_threat_register_section(updated)\n",
    1,
)

path.write_text(text, encoding="utf-8")
print(f"PATCHED: {path}")
PY

python3 -m py_compile "$TARGET"
python3 "$TARGET" --check

grep -q 'def update_threat_register_section' "$TARGET"
grep -q 'UN R155 requirements' "$TARGET"
grep -q 'Annex 5 analytical candidates' "$TARGET"

trap - ERR
printf '\nPATCH COMPLETE\n'
printf '  target : %s\n' "$TARGET"
printf '  backup : %s\n' "$BACKUP"
