#!/usr/bin/env python3
"""
generate_architecture_html.py — OCR (Open Code Review) architecture explainer.

Project-specific instance of the reusable template in
Visa-Vulnerablity Agentic Harness/templates/architecture-html/generate_architecture_html.py.
All SECTIONS/STAGES/MODULES content below was written from direct source reading of
samples/open-code-review/ (cmd/opencodereview, internal/agent, internal/scan,
internal/llmloop, internal/llm, internal/tool, internal/diff, internal/session,
internal/mcp, internal/delegate, internal/viewer) — not paraphrased from the README.

Regenerate after any source change:
    python3 tools/generate_architecture_html.py
Writes architecture.html and diagrams/module-graph.html at the project root.
"""
import os, re, html, json, datetime, pathlib

PROJECT_NAME = "Open Code Review (OCR)"
OUT_DIR = "."
DIAGRAMS_DIR = "diagrams"
SOURCE_REPO = "alibaba/open-code-review"

def svg(name):
    p = f"{DIAGRAMS_DIR}/{name}.svg"
    if not os.path.exists(p):
        return f"<p><em>[diagram {name} missing — render it or remove this reference]</em></p>"
    s = open(p, encoding="utf-8").read()
    s = s[s.find("<svg"):]
    s = re.sub(r'<svg ', '<svg style="max-width:100%;height:auto;" ', s, count=1)
    return s

SECTIONS = []
def sec(id, title, body):
    SECTIONS.append((id, title, body))

# ---------------------------------------------------------------------------
sec("overview", "1 · What OCR Is", """
<p class="lede">Open Code Review (OCR, CLI command <code>ocr</code>) is an AI-powered code
review tool. It reads a git diff (or, in full-scan mode, whole files), sends the changed
code to a configurable LLM through an agent that can call tools (read other files, search
the codebase), and produces structured, line-precise review comments — the same assistant
that started as Alibaba's internal review tool and has reviewed code for tens of thousands
of developers, now open source.</p>

<div class="callout plain simple-only">
  <h4>Explain-it-simply</h4>
  <p>Think of OCR as a very disciplined reviewer who is handed one changed file at a time,
  a stack of "read the neighboring file", "search the codebase", and "leave a comment"
  index cards (its tools), and a strict rulebook for how to write each comment down. The
  reviewer can look around before commenting, but every comment it writes must point at a
  real line, and a supervisor (deterministic engineering code, not the AI) decides which
  files the reviewer even sees and checks the reviewer's math on where each comment landed.</p>
</div>

<p>The core design bet, stated directly in the project's own README: a <b>purely
language-driven</b> agent (e.g. a general coding assistant given a "review this" skill)
tends to skip files on large changesets, mis-locate its own comments, and vary in quality
run to run. OCR's answer is <b>deterministic engineering + agent, each doing what it's
best at</b> — file selection, bundling, rule matching, and comment-location checking are
plain code with no model call in the loop; only the actual judgment of "is this a bug"
is left to the model. See §7 for exactly where that line falls in each package.</p>
""")

sec("audience", "2 · Who Should Read What", """
<p>Every module box in §7 below answers four questions when expanded: what happens, what
goes in/out, how the model (if any) is chosen, and what's deterministic vs. AI. Read at
whichever depth you need — the Simple/Technical switch above changes every description on
this page at once.</p>
<table class="tbl">
<tr><th>Reader</th><th>Start with</th><th>Then</th></tr>
<tr><td><b>Non-technical</b> (PM, analyst)</td><td>§1 Overview</td><td>§3 Context Diagram, then the "Explain-it-simply" boxes in §7</td></tr>
<tr><td><b>Security analyst</b></td><td>§4 Data Flow</td><td>§6 Trust Boundaries, §7 (tool + llm + viewer modules)</td></tr>
<tr><td><b>Junior developer</b></td><td>§5 Architecture (HLD)</td><td>§7 Module Flow → <code>docs/modules/README.md</code> for per-file detail</td></tr>
<tr><td><b>Reviewer / architect</b></td><td>§5 HLD</td><td>§8 Module Dependency Graph (real data) → <code>tool-outputs/</code></td></tr>
<tr><td><b>Operator</b> (wants to run <code>ocr</code>)</td><td><a href="https://open-codereview.ai/docs/quickstart">Quickstart</a></td><td><code>samples/open-code-review/README.md</code></td></tr>
</table>
""")

sec("context", "3 · Context Diagram (Who Talks to OCR)", f"""
<p>OCR runs entirely on the developer's machine (or a CI runner). It has exactly two
outbound network relationships: the configured LLM provider (HTTPS) and, only in
delegation mode, handing work to a coding agent the user already has running. Everything
else is local files.</p>
<div class="fig">{svg("03_context_dfd")}</div>
<p class="note">Click the diagram to zoom. Source: <code>diagrams/src/03_context_dfd.dot</code>.</p>
""")

sec("dataflow", "4 · Data Flow — `ocr review`", f"""
<p>This is the path one changed file takes through a normal <code>ocr review</code> run,
from git diff to a persisted comment.</p>
<div class="fig">{svg("02_dataflow_pipeline")}</div>
<div class="callout plain simple-only">
  <h4>Explain-it-simply</h4>
  <p>Every file gets its own mini-conversation with the AI. The AI can ask to see more code
  ("show me file X", "search for Y") before it decides to write a comment. Once it writes a
  comment, OCR double-checks the comment's line number against the real diff before
  accepting it — if the AI got confused about where something is, this catches it.</p>
</div>
<p>See §5 for the full-file scan (<code>ocr scan</code>) and delegation (<code>ocr
delegate</code>) variants of this flow.</p>
""")

sec("hld", "5 · Architecture (High-Level Design)", f"""
<div class="fig">{svg("01_architecture")}</div>
<table class="tbl">
<tr><th>#</th><th>Component</th><th>Package</th><th>Responsibility</th></tr>
<tr><td>1</td><td>CLI</td><td><code>cmd/opencodereview</code></td><td>Cobra commands: <code>review, scan, delegate, session, config, llm, rules, viewer, completion</code>. Resolves the LLM endpoint, loads config/rules, builds Args, dispatches.</td></tr>
<tr><td>2</td><td>Diff engine</td><td><code>internal/diff</code></td><td>Runs <code>git diff</code> (workspace / range / commit modes), parses unified diffs into hunks, respects <code>.gitignore</code>, resolves/relocates comment line numbers against the diff.</td></tr>
<tr><td>3</td><td>Config / rules</td><td><code>internal/config/{{rules,allowlist,template,toolsconfig}}</code></td><td>Path-based rule matching (which review rules apply to which files), file-type allowlist, prompt templates (<code>task_template.json</code>, <code>scan_template.json</code>), tool enable/disable config.</td></tr>
<tr><td>4</td><td>Review agent</td><td><code>internal/agent</code></td><td>Orchestrates diff review: loads diffs, filters, dispatches one goroutine per changed file (bounded concurrency), builds the manifest (coverage tracking for resume).</td></tr>
<tr><td>5</td><td>Scan agent</td><td><code>internal/scan</code></td><td>Orchestrates full-file review: enumerates files (whole repo or <code>--path</code>), same dispatch pattern, plus optional dedup and project-summary passes with no diff context.</td></tr>
<tr><td>6</td><td>Delegate</td><td><code>internal/delegate</code></td><td>Deterministic file selection + rule-group export for delegation mode — makes <b>no LLM call itself</b>; hands the work to the user's own coding agent.</td></tr>
<tr><td>7</td><td>LLM loop</td><td><code>internal/llmloop</code></td><td>The shared tool-use conversation loop (<code>Runner.RunPerFile</code>) used by both <code>agent</code> and <code>scan</code>: sends messages + tool defs, executes returned tool calls, tracks tokens, compresses context near the token limit, runs a final "grace round" when the round budget is exhausted.</td></tr>
<tr><td>8</td><td>Tools</td><td><code>internal/tool</code></td><td>The fixed toolset the model can call: <code>file_read, file_find, file_read_diff, code_search, code_comment, task_done</code>, plus a registry that can also hold dynamically-registered MCP tools.</td></tr>
<tr><td>9</td><td>MCP client</td><td><code>internal/mcp</code></td><td>Connects to user-configured MCP servers and adapts their tools into the same <code>tool.Registry</code> the built-in tools use — the model cannot tell a built-in tool from an MCP one.</td></tr>
<tr><td>10</td><td>LLM transport</td><td><code>internal/llm</code></td><td>Resolves which provider/protocol/model to call (env vars → <code>config.json</code> → built-in provider presets), speaks Anthropic / OpenAI Chat Completions / OpenAI Responses protocols, retries with backoff, records a per-run retry report.</td></tr>
<tr><td>11</td><td>Session</td><td><code>internal/session</code></td><td>Per-run history (JSONL), the coverage <b>manifest</b> (which files completed/reused/failed and why), resume support (re-run only what didn't finish).</td></tr>
<tr><td>12</td><td>Viewer</td><td><code>internal/viewer</code></td><td>A local-only web server that renders session JSONL as browsable HTML — comments, token usage, tool-call timeline.</td></tr>
<tr><td>13</td><td>Telemetry</td><td><code>internal/telemetry</code></td><td>OpenTelemetry spans/metrics/events around diff parsing, LLM calls, and tool calls — opt-in observability, not a code path any review result depends on.</td></tr>
</table>
""")

sec("trust", "6 · Trust Boundaries & Security Posture", """
<p>From the project's own <code>ASSURANCE_CASE.md</code> (source-verified, not summarized
from marketing copy):</p>
<table class="tbl">
<tr><th>Boundary</th><th>Risk</th><th>Mitigation</th></tr>
<tr><td>Git repo → CLI</td><td>Crafted diff content</td><td>Strict unified-diff parsing; every external process call is <code>git</code> with a hardcoded subcommand list and <code>--end-of-options</code> — no shell, no shell interpolation.</td></tr>
<tr><td>CLI → LLM provider</td><td>API key leakage</td><td>Keys read only from environment variables; never logged, written to output, or sent anywhere but the configured endpoint.</td></tr>
<tr><td>LLM response → local file</td><td>Path traversal from a model-suggested path</td><td><code>pathutil.WithinBase()</code> validates every file-tool path against the repo root, before and after symlink resolution.</td></tr>
<tr><td>Browser → viewer</td><td>DNS rebinding against the local session viewer</td><td>Host-header allowlist rejects non-loopback origins by default (<code>OCR_VIEWER_ALLOWED_HOSTS</code> to override); strict CSP and security headers on every response.</td></tr>
<tr><td>Network</td><td>MITM on the API call</td><td>Go's default TLS 1.2+ with full certificate verification; <code>InsecureSkipVerify</code> is never set.</td></tr>
</table>
<p class="note">CGO is disabled (<code>CGO_ENABLED=0</code>) — the release binaries are
memory-safe Go with no C attack surface, and the Go race detector runs in CI.</p>
""")

from ocr_module_data import STAGES, MODULES  # noqa: E402

sec("stepper", "5b · Interactive Review Lifecycle", """
<p>Click a stage to see its role and exactly which config key or absence of one decides
whether a model gets called. This is the per-file lifecycle both <code>ocr review</code>
and <code>ocr scan</code> run through (scan has no diff, so it works from whole-file
content instead — see §7's <code>internal/scan</code> box for what differs).</p>
<div id="stepper"><div class="chips" id="chips"></div><div class="stagecard" id="stagecard"></div></div>
<script id="stagedata" type="application/json">%STAGES%</script>
""")

def moduleflow_html():
    from collections import OrderedDict
    layers = OrderedDict()
    for m in MODULES:
        layers.setdefault(m["layer"], []).append(m)
    parts = ['<div class="mflow">']
    layer_keys = list(layers.keys())
    for li, lk in enumerate(layer_keys):
        parts.append(f'<div class="mlayer"><div class="mlayer-label">{html.escape(lk)}</div><div class="mrow">')
        for m in layers[lk]:
            parts.append(
              f'<details class="mbox" style="border-top:4px solid {m["color"]}">'
              f'<summary>'
              f'<span class="mname">{html.escape(m["name"])} <span class="caret">▸</span></span>'
              f'<span class="mio"><b>in</b> {html.escape(m["in"])}</span>'
              f'<span class="mio"><b>out</b> {html.escape(m["out"])}</span>'
              f'<span class="mexpand">click to expand</span>'
              f'</summary>'
              f'<div class="mdetail">'
              f'<p><span class="badge">package: {html.escape(m["pkg"])}</span></p>'
              f'<p>{html.escape(m["role"])}</p>'
              f'<div class="io"><div><b>Input</b>{html.escape(m["in"])}</div>'
              f'<div><b>Output</b>{html.escape(m["out"])}</div></div>'
              f'<div class="msub"><h5>What actually happens here</h5><p>{html.escape(m.get("detail",""))}</p></div>'
              f'<div class="msub msub-model"><h5>How the LLM / model version is chosen</h5><p>{html.escape(m.get("model",""))}</p></div>'
              f'<div class="msub msub-det"><h5>Deterministic (non-LLM) work in this module</h5><p>{html.escape(m.get("deterministic",""))}</p></div>'
              f'<p class="dep"><b>Depends on:</b> {html.escape(m["dep"]) or "(none — leaf package)"}</p>'
              f'</div></details>')
        parts.append('</div></div>')
        if li < len(layer_keys) - 1:
            parts.append('<div class="marrow">▼</div>')
    parts.append('</div>')
    return "".join(parts)

sec("moduleflow", "7 · Module Flow", """
<p>Click any box below to expand what actually happens inside it, how its model (if any)
is selected, and which parts are deterministic. Thirteen packages, grouped into seven
layers from CLI entry down to persistence/observability.</p>
<div id="moduleflow">%MODULEFLOW%</div>
""")

sec("moddeps", "8 · Module Dependency Graph (real data)", f"""
<p>Rendered from a CodeGraph SQLite index of the actual repository (7,416 nodes, 23,976
edges across 435 files) — not hand-drawn. Top 28 module-to-module edges by call/reference
weight; full data in <code>tool-outputs/codegraph/module_dependencies.json</code>.</p>
<div class="fig">{svg("04_module_dependencies")}</div>
<p class="note">The heaviest edge, <code>cmd/opencodereview → internal/llm</code> (492), is
almost entirely the CLI's config/provider/TUI code exercising <code>internal/llm</code>'s
endpoint-resolution types — expected, since the CLI owns provider setup. The next heaviest,
<code>internal/llmloop → internal/llm</code> (253) and <code>internal/agent → internal/llm</code>
(176), are the actual chat-completion call sites.</p>
""")

sec("modes", "9 · The Three Review Modes, Side by Side", f"""
<div class="fig">{svg("05_scan_and_delegate")}</div>
<table class="tbl">
<tr><th>Mode</th><th>Command</th><th>Input unit</th><th>Needs OCR-configured LLM?</th><th>Extra phases vs. review</th></tr>
<tr><td>Diff review</td><td><code>ocr review</code></td><td>per-file unified diff</td><td>Yes</td><td>—</td></tr>
<tr><td>Full-file scan</td><td><code>ocr scan</code></td><td>whole file content, batched</td><td>Yes</td><td>optional dedup task, optional project-summary task</td></tr>
<tr><td>Delegation</td><td><code>ocr delegate</code></td><td>rule groups + file list</td><td><b>No</b></td><td>review itself runs inside the user's own coding agent</td></tr>
</table>
""")

# ==== TEMPLATE (do not edit below this line) ================================
body_html = ""; nav_html = ""
for id, title, body in SECTIONS:
    body = body.replace("%STAGES%", json.dumps(STAGES)).replace("%MODULEFLOW%", moduleflow_html())
    nav_html += f'<a href="#{id}" data-nav="{id}">{title}</a>\n'
    body_html += f'<section id="{id}"><h2>{title}</h2>{body}</section>\n'

TEMPLATE = """<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>%PROJECT% — Architecture Explainer</title>
<style>
:root{--bg:#0f1419;--panel:#fff;--ink:#1a2027;--mut:#5b6773;--line:#e3e8ee;
--accent:#1a56db;--accent2:#137333;--warn:#b45309;--danger:#b00020;--soft:#f6f8fb;}
*{box-sizing:border-box}
body{margin:0;font:16px/1.65 -apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
color:var(--ink);background:var(--soft);}
header.top{background:linear-gradient(120deg,#0f1e3d,#1a56db);color:#fff;padding:34px 40px;}
header.top h1{margin:0 0 6px;font-size:27px;letter-spacing:.2px}
header.top p{margin:0;opacity:.9;font-size:15px}
.wrap{display:flex;align-items:flex-start;max-width:1200px;margin:0 auto}
nav.side{position:sticky;top:0;align-self:flex-start;width:250px;padding:26px 14px;
font-size:14px;max-height:100vh;overflow:auto}
nav.side a{display:block;color:var(--mut);text-decoration:none;padding:7px 12px;border-radius:8px;margin-bottom:2px}
nav.side a:hover{background:#eef2f8;color:var(--accent)}
main{flex:1;min-width:0;padding:26px 34px 90px}
section{background:var(--panel);border:1px solid var(--line);border-radius:14px;
padding:26px 30px;margin-bottom:22px;box-shadow:0 1px 2px rgba(16,24,40,.04)}
h2{margin:.1em 0 .7em;font-size:22px;border-bottom:2px solid var(--line);padding-bottom:10px}
h4{margin:1.1em 0 .4em;font-size:16px}
.lede{font-size:18px;line-height:1.6}
code{background:#eef2f7;padding:1px 6px;border-radius:5px;font-size:.88em;
font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
.callout{border-radius:10px;padding:14px 18px;margin:16px 0;border-left:5px solid var(--accent)}
.callout h4{margin:.1em 0 .3em}
.callout.plain{background:#eef4ff;border-color:var(--accent)}
.callout.warn{background:#fff7ed;border-color:var(--warn)}
.phase{border:1px solid var(--line);border-left:5px solid var(--accent2);border-radius:10px;padding:12px 18px;margin:12px 0;background:#f4faf6}
.phase.danger{border-left-color:var(--danger);background:#fdf3f4}
.fig{text-align:center;margin:18px 0;padding:14px;background:#fbfcfe;border:1px solid var(--line);border-radius:10px;overflow:auto;cursor:zoom-in}
.note{color:var(--mut);font-size:14px}
table.tbl{border-collapse:collapse;width:100%;margin:12px 0;font-size:14.5px}
table.tbl th,table.tbl td{border:1px solid var(--line);padding:8px 11px;text-align:left;vertical-align:top}
table.tbl th{background:#f1f5fb}
.grid3{display:flex;gap:14px;margin:18px 0;flex-wrap:wrap}
.stat{flex:1;min-width:150px;background:#0f1e3d;color:#fff;border-radius:12px;padding:16px;text-align:center;font-size:13px}
.stat span{display:block;font-size:30px;font-weight:700;margin-bottom:2px}
ul{margin:.4em 0 .4em 1.1em}
footer{max-width:1200px;margin:0 auto;padding:10px 34px 50px;color:var(--mut);font-size:13px}
@media(max-width:820px){nav.side{display:none}main{padding:18px}}
.toolbar{display:flex;gap:10px;align-items:center;margin-top:14px;flex-wrap:wrap}
.switch{display:inline-flex;background:rgba(255,255,255,.15);border-radius:999px;padding:3px}
.switch button{border:0;background:transparent;color:#fff;padding:6px 16px;border-radius:999px;cursor:pointer;font-size:13px;font-weight:600}
.switch button.on{background:#fff;color:#0f1e3d}
nav.side a.active{background:#e7eefc;color:var(--accent);font-weight:600}
.chips{display:flex;flex-wrap:wrap;gap:8px;margin:8px 0 16px}
.chip{cursor:pointer;border:1px solid var(--line);border-radius:10px;padding:8px 12px;font-size:13px;font-weight:600;background:#fff;transition:.15s;user-select:none}
.chip:hover{border-color:var(--accent)}
.chip.on{color:#fff;border-color:transparent;background:var(--accent)}
.stagecard{border:1px solid var(--line);border-radius:12px;padding:18px 20px;background:#fbfcfe;min-height:120px}
.stagecard h3{margin:.1em 0 .5em;font-size:19px}
.stagecard .io{display:flex;gap:14px;flex-wrap:wrap;margin-top:12px}
.stagecard .io div{flex:1;min-width:180px;background:#fff;border:1px solid var(--line);border-radius:9px;padding:10px 12px;font-size:13px}
.stagecard .io b{display:block;color:var(--mut);font-size:11px;text-transform:uppercase;letter-spacing:.4px;margin-bottom:3px}
.badge{display:inline-block;font-size:11px;font-weight:700;padding:2px 9px;border-radius:999px;background:#eef2f8;color:#334;margin-right:6px}
.lightbox{position:fixed;inset:0;background:rgba(6,10,20,.9);display:none;align-items:center;justify-content:center;z-index:99;padding:24px}
.lightbox.open{display:flex}
.lightbox .inner{background:#fff;border-radius:10px;padding:14px;max-width:96vw;max-height:94vh;overflow:auto}
body.mode-simple .tech-only{display:none}
body.mode-tech .simple-only{display:none}
.jumpbtn{position:fixed;right:18px;bottom:18px;background:var(--accent);color:#fff;border:0;border-radius:999px;padding:12px 16px;cursor:pointer;box-shadow:0 4px 14px rgba(16,24,40,.3);font-size:13px;display:none}
.jumpbtn.show{display:block}
/* module flow — zero-JS expand via native <details> */
.mflow{display:flex;flex-direction:column;align-items:center;gap:2px;margin:10px 0}
.mlayer{width:100%;background:#fbfcfe;border:1px solid var(--line);border-radius:12px;padding:10px 12px}
.mlayer-label{font-size:11px;font-weight:700;letter-spacing:.5px;text-transform:uppercase;color:var(--mut);margin-bottom:8px}
.mrow{display:flex;gap:10px;flex-wrap:wrap;justify-content:center}
.mbox{flex:1;min-width:220px;max-width:440px;background:#fff;border:1px solid var(--line);border-radius:10px;transition:.15s}
.mbox>summary{list-style:none;cursor:pointer;padding:10px 12px;display:flex;flex-direction:column;gap:3px}
.mbox>summary::-webkit-details-marker{display:none}
.mbox>summary::marker{content:""}
.mbox:hover{box-shadow:0 3px 12px rgba(16,24,40,.12)}
.mbox[open]{box-shadow:0 4px 16px rgba(16,24,40,.15);outline:2px solid var(--accent);outline-offset:1px}
.mbox[open] .caret{transform:rotate(90deg)}
.caret{display:inline-block;transition:transform .15s;color:var(--accent);font-size:.8em}
.mname{font-weight:700;font-size:14px}
.mio{font-size:11.5px;color:var(--mut);line-height:1.35}
.mio b{color:#334;text-transform:uppercase;font-size:10px;letter-spacing:.3px}
.mexpand{font-size:10.5px;color:var(--accent);margin-top:2px}
.mdetail{padding:4px 14px 14px;border-top:1px dashed var(--line);margin-top:4px}
.mdetail .io{display:flex;gap:12px;flex-wrap:wrap;margin:10px 0}
.mdetail .io div{flex:1;min-width:180px;background:#f7faff;border:1px solid var(--line);border-radius:9px;padding:9px 12px;font-size:13px}
.mdetail .io b{display:block;color:var(--mut);font-size:10px;text-transform:uppercase;letter-spacing:.4px;margin-bottom:3px}
.mdetail .dep{font-size:12.5px;color:var(--mut);margin:.3em 0 0}
.msub{margin:10px 0;padding:9px 12px;border-radius:9px;background:#f7faff;border:1px solid var(--line)}
.msub h5{margin:0 0 4px;font-size:10.5px;text-transform:uppercase;letter-spacing:.4px;color:var(--accent)}
.msub p{margin:0;font-size:13px;line-height:1.55}
.msub-model{background:#fdf6e9;border-color:#eddfb8}
.msub-model h5{color:var(--warn)}
.msub-det{background:#eefaf1;border-color:#c9ecd4}
.msub-det h5{color:var(--accent2)}
.marrow{color:#9aa4b2;font-size:15px;line-height:1}
</style></head>
<body>
<header class="top">
  <h1>%PROJECT% — Architecture Explainer</h1>
  <p>generated %DATE% · onboarding companion, not the source of truth</p>
  <div class="toolbar">
    <span style="font-size:13px;opacity:.9">Reading level:</span>
    <span class="switch" id="modeswitch">
      <button data-mode="simple" class="on">Simple</button>
      <button data-mode="tech">Technical</button>
    </span>
  </div>
</header>
<div class="wrap">
  <nav class="side">%NAV%</nav>
  <main>%BODY%</main>
</div>
<footer>Generated for onboarding from <code>%REPO%</code>. This is an explanatory
companion — the code in <code>samples/open-code-review/</code> is the source of truth.</footer>
<button class="jumpbtn" id="jump">↑ Top</button>
<div class="lightbox" id="lightbox"><div class="inner" id="lightboxInner"></div></div>
<script>
(function(){
  var body=document.body; body.classList.add('mode-simple');
  var mode='simple';
  document.querySelectorAll('#modeswitch button').forEach(function(b){
    b.addEventListener('click',function(){
      mode=b.dataset.mode;
      document.querySelectorAll('#modeswitch button').forEach(function(x){x.classList.toggle('on',x===b);});
      body.classList.toggle('mode-simple',mode==='simple');
      body.classList.toggle('mode-tech',mode==='tech');
      if(cur) drawCard(cur);
    });
  });
  var stagedataEl=document.getElementById('stagedata');
  var data = stagedataEl ? JSON.parse(stagedataEl.textContent) : [];
  var chips=document.getElementById('chips'), card=document.getElementById('stagecard'), cur=null;
  if (chips) {
    data.forEach(function(s){
      var c=document.createElement('div'); c.className='chip'; c.dataset.id=s.id;
      c.innerHTML=s.id+'<small>'+s.name+'</small>';
      c.addEventListener('click',function(){select(s);});
      chips.appendChild(c);
    });
    function select(s){
      cur=s;
      document.querySelectorAll('.chip').forEach(function(c){c.classList.toggle('on',c.dataset.id===s.id);});
      drawCard(s);
    }
    function drawCard(s){
      var desc = mode==='tech' ? s.tech : s.simple;
      card.innerHTML='<h3>'+s.id+' · '+s.name+'</h3>'+
        '<div><span class="badge">skill: '+s.skill+'</span><span class="badge">backend: '+s.backend+'</span></div>'+
        '<p style="margin:.7em 0 .2em">'+desc+'</p>'+
        '<div class="io"><div><b>Input</b>'+s['in']+'</div><div><b>Output</b>'+s.out+'</div></div>';
    }
    if (data.length) select(data[0]);
  }
  // module flow boxes use native <details> — no JS needed to expand.
  var lb=document.getElementById('lightbox'), lbi=document.getElementById('lightboxInner');
  document.querySelectorAll('.fig').forEach(function(f){
    f.addEventListener('click',function(){ lbi.innerHTML=f.innerHTML; lb.classList.add('open'); });
  });
  lb.addEventListener('click',function(){ lb.classList.remove('open'); lbi.innerHTML=''; });
  var links=[].slice.call(document.querySelectorAll('nav.side a'));
  var secs=links.map(function(a){return document.getElementById(a.dataset.nav);});
  var jump=document.getElementById('jump');
  function onScroll(){
    var y=window.scrollY+130, idx=0;
    secs.forEach(function(sc,i){ if(sc && sc.offsetTop<=y) idx=i; });
    links.forEach(function(a,i){a.classList.toggle('active',i===idx);});
    jump.classList.toggle('show',window.scrollY>500);
  }
  window.addEventListener('scroll',onScroll,{passive:true}); onScroll();
  jump.addEventListener('click',function(){window.scrollTo({top:0,behavior:'smooth'});});
})();
</script>
</body></html>"""

out = (TEMPLATE.replace("%NAV%", nav_html)
               .replace("%BODY%", body_html)
               .replace("%PROJECT%", PROJECT_NAME)
               .replace("%REPO%", SOURCE_REPO)
               .replace("%DATE%", datetime.date.today().isoformat()))
pathlib.Path(OUT_DIR).mkdir(parents=True, exist_ok=True)
open(f"{OUT_DIR}/architecture.html", "w", encoding="utf-8").write(out)
print("wrote architecture.html", len(out), "bytes")

STANDALONE = """<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>%PROJECT% — Interactive Module Graph</title>
<style>
body{margin:0;font:16px/1.6 -apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;color:#1a2027;background:#f6f8fb}
header{background:linear-gradient(120deg,#0f1e3d,#1a56db);color:#fff;padding:24px 30px}
header h1{margin:0 0 4px;font-size:22px}header p{margin:0;opacity:.9;font-size:14px}
main{max-width:1100px;margin:0 auto;padding:22px}
:root{--line:#e3e8ee;--mut:#5b6773;--accent:#1a56db}
%CSS%
.hint{color:var(--mut);font-size:13px;margin:6px 0 14px}
</style></head><body>
<header><h1>%PROJECT% — Interactive Module Graph</h1>
<p>Click any box to expand its input, output, model routing, and deterministic details.</p></header>
<main>
<p class="hint">A lightweight, readable view of the modules — use this instead of a raw
graph-tool export, which is usually too dense for a human to read directly.</p>
%FLOW%
</main>
</body></html>"""
css_block = TEMPLATE.split("/* module flow")[1].split("</style>",1)[0]
sa = (STANDALONE.replace("%CSS%", "/* module flow" + css_block)
                .replace("%FLOW%", moduleflow_html())
                .replace("%PROJECT%", PROJECT_NAME))
pathlib.Path(DIAGRAMS_DIR).mkdir(parents=True, exist_ok=True)
open(f"{DIAGRAMS_DIR}/module-graph.html", "w", encoding="utf-8").write(sa)
print("wrote", f"{DIAGRAMS_DIR}/module-graph.html", len(sa), "bytes")
