#!/usr/bin/env python3
"""
gen_module_docs.py — one Markdown file per OCR package, in the same
plain-English-first/technical-second format as VVAH's docs/modules/*.md
(see Visa-Vulnerablity Agentic Harness/templates/module-docs/module_doc_template.md).

Reads MODULES from ocr_module_data.py (the single source of truth also used by
generate_architecture_html.py) — never hand-edit an output .md file here; edit
ocr_module_data.py and re-run this script.

Usage: python3 tools/gen_module_docs.py
Writes docs/modules/<id>.md for every entry in MODULES, plus regenerates
docs/modules/README.md's per-module table (left untouched here — see that file).
"""
import os
from ocr_module_data import MODULES

PROJ = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT_DIR = os.path.join(PROJ, "docs", "modules")

by_id = {m["id"]: m for m in MODULES}


def deps_list(dep_str):
    return [d.strip() for d in dep_str.split(",") if d.strip()]


def dependents_of(module_id):
    return sorted(m["name"] for m in MODULES if module_id in deps_list(m["dep"]))


def render(m):
    dep_ids = deps_list(m["dep"])
    dep_names = ", ".join(f"`{d}`" for d in dep_ids) if dep_ids else "*(none — leaf package)*"
    dependents = dependents_of(m["id"])
    dependents_str = ", ".join(f"`{d}`" for d in dependents) if dependents else "*(nothing in this package set imports it directly — used only by the CLI entry point or externally)*"

    mini_flow = (
        "```mermaid\n"
        "flowchart LR\n"
        f'  IN["Input\\n{m["in"]}"] --> ACT["{m["name"]}\\n{m["role"]}"]\n'
        f'  ACT --> OUT["Output\\n{m["out"]}"]\n'
        "```\n"
    )

    body = f"""# Open Code Review (OCR) — {m["name"]}

{mini_flow}
{m["role"]} Package: `{m["pkg"]}`.

### What flows through it

```mermaid
flowchart LR
  IN["{m["in"]}"] --> MOD["{m["name"]}"]
  MOD --> OUT["{m["out"]}"]
```

---

## Technical details

**Package:** `{m["pkg"]}`
**Depends on:** {dep_names}
**Depended on by:** {dependents_str}

### What actually happens here

{m.get("detail", "")}

### How the LLM / model version is chosen

{m.get("model", "")}

### Deterministic (non-LLM) work in this module

{m.get("deterministic", "")}

---

Part of the [module docs index](README.md). Full interactive version, with every module
side by side: [`architecture.html`](../../architecture.html) §7. Cross-cutting mechanisms
this module participates in (retry, compression, manifest, resume, hashing): [LLD](../design/LLD.md).
"""
    return body


os.makedirs(OUT_DIR, exist_ok=True)
for m in MODULES:
    path = os.path.join(OUT_DIR, f"{m['id']}.md")
    open(path, "w", encoding="utf-8").write(render(m))
    print("wrote", os.path.relpath(path, PROJ))

print(f"\n{len(MODULES)} module docs written to docs/modules/")
