#!/usr/bin/env python3
"""Build index.html, the project landing page.

Shares scripts/tokens.css with the figure, so the two pages cannot drift, and
derives its headline numbers from figures/moat_data.json rather than hardcoding
them, so the page cannot go stale against the data. Deterministic: no build date,
no clock -- rerunning reproduces the file byte-for-byte.
"""
import json, os

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

D = json.load(open(os.path.join(ROOT, "figures", "moat_data.json")))
TPL = open(os.path.join(ROOT, "scripts", "index_template.html")).read()
TOKENS = open(os.path.join(ROOT, "scripts", "tokens.css")).read()

moat = D["gaps"][0]
nearest = min(p["d"] for p in D["pts"] if not p["sihek"])
within = max(p["d"] for p in D["pts"] if p["sihek"])

stats = [
    (str(D["n"]), "ND2 sequences"),
    ("0", "sequences in the moat"),
    (f'{moat["w"]:.2f}<span class="u"> pp</span>', "width of the void"),
    (f'{nearest:.2f}<span class="u"> %</span>', "nearest other kingfisher"),
    (str(len(D["gaps"])), "empty annuli in the family"),
]
stats_html = "".join(f'<div class="stat"><div class="v">{v}</div><div class="k">{k}</div></div>'
                     for v, k in stats)

out = (TPL.replace("/*TOKENS*/", TOKENS)
          .replace("<!--STATS-->", stats_html)
          .replace("<!--MOATW-->", f'{moat["w"]:.2f}')
          .replace("<!--BUILT-->", f'from {D["n"]} ND2 sequences'))

for marker in ("/*TOKENS*/", "<!--STATS-->", "<!--MOATW-->", "<!--BUILT-->"):
    assert marker not in out, f"unfilled placeholder {marker}"
non_ascii = sorted({c for c in out if ord(c) > 127})
assert not non_ascii, f"non-ASCII characters present: {non_ascii}"

path = os.path.join(ROOT, "index.html")
open(path, "w").write(out)
print(f"wrote {path}  {len(out)} bytes")
print(f"  moat {moat['lo']:.2f}-{moat['hi']:.2f}% ({moat['w']:.2f} pp), "
      f"nearest {nearest:.4f}%, within-sihek max {within:.4f}%, {len(D['gaps'])} voids")
