#!/usr/bin/env python3
"""Write docs/CONVERGENCE.md from data/graph.json, data/sources.json and results/certificate.json.

The map is generated so that it cannot drift from the checked data. Run after `python3 verify.py --write`.
"""
from __future__ import annotations

import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
graph = json.loads((ROOT / "data" / "graph.json").read_text(encoding="utf-8"))
sources = json.loads((ROOT / "data" / "sources.json").read_text(encoding="utf-8"))["repos"]
cert = json.loads((ROOT / "results" / "certificate.json").read_text(encoding="utf-8"))
nodes = {n["id"]: n for n in graph["nodes"]}


def link(repo: str) -> str:
    return f"[{repo}](https://github.com/{repo})"


def where(c: dict) -> str:
    commit = sources[c["repo"]]["commit"]
    return f"[{c['repo'].split('/')[1]}/{c['path']}:{c['line']}](https://github.com/{c['repo']}/blob/{commit}/{c['path']}#L{c['line']})"


def pin(repo: str) -> str:
    if repo in sources:
        return f"`{sources[repo]['commit'][:7]}`"
    return "this repository" if repo == "aska-physical/optifab" else "named only, not read"


out: list[str] = []
w = out.append
g = cert["graph"]
w("# Convergence map")
w("")
w("Generated by `tools/render_map.py` from `data/graph.json`. Do not edit by hand.")
w("")
w(f"This is the work across aska-physical, Foundation-0, Moissanite-Labs and Proven-Commons that bears on a data "
  f"centre and the intelligence it runs: {g['nodes']} repositories and {g['edges']} links. Every link cites the line "
  f"that states it, at a pinned commit. `python3 verify.py --upstream ROOT` re-reads every cited line.")
w("")
w("Each status below is the repository's own, in its own words or a close paraphrase. Where a repository does not use "
  "the Foundation-0 Ledger's words, the evidence level in the stack table was assigned here and says so.")
w("")
w("## The stack, layer by layer")
for layer, title in graph["layers"].items():
    rows = [n for n in graph["nodes"] if n["layer"] == layer]
    w("")
    w(f"### {layer}. {title}")
    w("")
    w("| Repository | What it is | Status | Pinned |")
    w("|---|---|---|---|")
    for n in sorted(rows, key=lambda n: n["id"].lower()):
        status = n.get("status", "")
        if n.get("status_cite"):
            status += f" ({where(n['status_cite'])})"
        w(f"| {link(n['id'])} | {n['role']} | {status} | {pin(n['id'])} |")

w("")
w("## Links")
w("")
w("Link types:")
w("")
for name, text in graph["edge_types"].items():
    w(f"- `{name}`: {text}")


def table(title: str, rows: list[dict], intro: str = "") -> None:
    w("")
    w(f"### {title}")
    w("")
    if intro:
        w(intro)
        w("")
    w("| From | To | Type | Stated at | Note |")
    w("|---|---|---|---|---|")
    for e in rows:
        w(f"| {e['src']} | {e['dst']} | `{e['type']}` | {where(e['cite'])} | {e.get('note', '')} |")


def org(i: str) -> str:
    return i.split("/")[0]


new = [e for e in graph["edges"] if e.get("new")]
cross = [e for e in graph["edges"] if not e.get("new") and org(e["src"]) != org(e["dst"])]
inside = [e for e in graph["edges"] if not e.get("new") and org(e["src"]) == org(e["dst"])]
table("Added by optifab v0.1.0", new,
      f"Before this version the graph holds {g['aska_physical_to_moissanite_links_before']} links between aska-physical "
      "and Moissanite-Labs, and a search of the other three organisations' repositories for aska-physical or its "
      "data-centre work finds nothing. The Weft link below is the first.")
table("Between organisations, already in place", cross)
table("Inside one organisation", inside)

w("")
w("## Evidence in the physical stack")
w("")
w(f"The physical stack is optifab and everything it builds on in layers L0 to L3: {g['stack_size']} repositories. "
  "The scale is the Foundation-0 Ledger's: claimed 1, preprint 2, peer reviewed or deployed 3, independently "
  "replicated 4, formally verified 5.")
w("")
w("| Repository | Evidence | Assigned by | Repositories downstream in the stack |")
w("|---|---|---|---|")
for r in g["stack"]:
    w(f"| {r['node']} | {r['evidence']} | {r.get('assigned_by', '')} | {r['downstream_in_stack']} |")
w("")
counts = ", ".join(f"{v} {k}" for k, v in g["stack_by_evidence"].items())
w(f"Counts: {counts}. Nothing in the stack is peer reviewed, replicated, deployed or formally verified. "
  "An independent replication does most good at the top of this table, where the most downstream work rests on it.")

w("")
w("## Surveyed and not connected")
w("")
w("These were read in the same pass. They are listed so the next reader does not repeat the search.")
w("")
w("| Repository | Why it is not in the stack |")
w("|---|---|")
for s in graph["surveyed_not_connected"]:
    w(f"| {link(s['repo'])} | {s['why']} |")

w("")
w("## Pinned commits")
w("")
w("| Repository | Commit |")
w("|---|---|")
for repo in sorted(sources, key=str.lower):
    w(f"| {repo} | `{sources[repo]['commit']}` |")
w("")
(ROOT / "docs" / "CONVERGENCE.md").write_text("\n".join(out), encoding="utf-8")
print(f"wrote docs/CONVERGENCE.md ({len(out)} lines)")

# ---------------------------------------------------------------- docs/STRUCTURE.md: fill the generated blocks
unit = json.loads((ROOT / "data" / "unit.json").read_text(encoding="utf-8"))


def short(repo: str) -> str:
    return f"[{repo.split('/')[1] if not repo.endswith('/.github') else repo}](https://github.com/{repo})"


blocks: dict[str, list[str]] = {}
b = blocks.setdefault("unit", [])
for organ in unit["organs"]:
    b += ["", f"### {organ}", "", "| | Element | Where in the structure | Work it rests on | Status | Note |", "|---|---|---|---|---|---|"]
    for e in unit["elements"]:
        if e["organ"] == organ:
            repos = ", ".join(short(x) for x in e["repos"]) or "none"
            b.append(f"| {e['id']} | {e['element']} | {e['where']} | {repos} | {e['status']} | {e['note']} |")
b += ["", "Status words:", ""] + [f"- `{k}`: {v}" for k, v in unit["statuses"].items()]

b = blocks.setdefault("loop", [])
b += ["| | From | To | Status | Note |", "|---|---|---|---|---|"]
b += [f"| {i['id']} | {i['from']} | {i['to']} | {i['status']} | {i['note']} |" for i in unit["interfaces"]]

b = blocks.setdefault("notplaced", [])
b += ["| Repository | Why it has no place in the structure |", "|---|---|"]
b += [f"| {link(x['repo'])} | {x['why']} |" for x in unit["not_placed"]]

u = cert["unit"]
b = blocks.setdefault("count", [])
orgs = ", ".join(f"{v} from {k}" for k, v in u["repositories_placed_by_org"].items())
stat = ", ".join(f"{v} {k}" for k, v in u["elements_by_status"].items())
loop = ", ".join(f"{v} {k}" for k, v in u["loop_interfaces_by_status"].items())
b += [f"- **Placed:** {u['repositories_placed']} of {g['nodes']} repositories ({orgs}). {u['repositories_not_placed']} have no place and say why.",
      f"- **Elements:** {u['elements']} ({stat}).",
      f"- **Loop:** {u['loop_interfaces']} interfaces ({loop}). The loop is {'closed' if u['loop_closed'] else 'open'}.",
      f"- **Elements with nothing behind them:** {', '.join(u['elements_with_no_repository'])}."]

f = cert["plant_frame"]
b = blocks.setdefault("frame", [])
b += ["| Slot | Content |", "|---|---|"] + [f"| {i} | `{name}` |" for i, name in enumerate(f["slots"])]
b += ["", "| Frame | What the contract check reports |", "|---|---|"]
b += [f"| {k} | {', '.join(f'`{x}`' for x in v) or 'nothing: every term holds'} |" for k, v in f["contract_check"].items()]

tm = cert["loop_timing"]
b = blocks.setdefault("timing", [])
b += [f"| Plant tone | Delay at {tm['slow_latency_ms']:g} ms, in cycles | Effect at {tm['slow_latency_ms']:g} ms | Delay at {tm['fast_latency_ms']:g} ms, in cycles | Effect at {tm['fast_latency_ms']:g} ms | Longest delay that helps within the cycle |",
      "|---|---|---|---|---|---|"]
b += [f"| {r['tone_Hz']:g} Hz | {r['cycles_of_delay_slow']:g} | {r['change_dB_slow']:+.1f} dB | {r['cycles_of_delay_fast']:g} | {r['change_dB_fast']:+.1f} dB | {r['longest_delay_that_helps_within_the_cycle_ms']:g} ms |"
      for r in tm["plant_tones"]]

path = ROOT / "docs" / "STRUCTURE.md"
text = path.read_text(encoding="utf-8")
for name, lines in blocks.items():
    start, end = f"<!-- {name}:begin -->", f"<!-- {name}:end -->"
    if start not in text or end not in text:
        raise SystemExit(f"docs/STRUCTURE.md has no {name} block")
    head, rest = text.split(start, 1)
    text = head + start + "\n" + "\n".join(lines).strip("\n") + "\n" + end + rest.split(end, 1)[1]
path.write_text(text, encoding="utf-8")
print(f"filled {len(blocks)} blocks in docs/STRUCTURE.md")
