#!/usr/bin/env python3
import json, re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SLUG = "rsi-ai-first-blockchain-capital-machine-proof"
TITLE = "AI-First Blockchain Capital Machine"
PROOF_NAME = "Autonomous RSI AI-First Blockchain Capital Machine Proof"
MARK_START = "<!-- skillos-ai-first-blockchain-capital-machine:start -->"
MARK_END = "<!-- skillos-ai-first-blockchain-capital-machine:end -->"


def money(x):
    if abs(x) >= 1e12: return f"${x/1e12:,.2f}T"
    if abs(x) >= 1e9: return f"${x/1e9:,.2f}B"
    return f"${x:,.0f}"


def pct(x):
    return f"{x*100:,.3f}%"


def default_index(section):
    return f'''<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>SkillOS Proof Command Center</title><style>
body{{margin:0;background:linear-gradient(135deg,#061420,#10243b 48%,#282a61);color:#ecfbff;font-family:Inter,system-ui,Segoe UI,Arial,sans-serif}}body:before{{content:"";position:fixed;inset:0;background-image:linear-gradient(rgba(255,255,255,.045) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.045) 1px,transparent 1px);background-size:34px 34px;pointer-events:none}}a{{color:#83f7ff;text-decoration:none}}nav{{position:sticky;top:0;background:#061420e8;border-bottom:1px solid rgba(255,255,255,.18);padding:14px 22px;display:flex;justify-content:space-between;z-index:2}}.brand{{font-weight:950;color:#83f7ff}}main{{max-width:1180px;margin:auto;padding:40px 22px 80px}}h1{{font-size:clamp(48px,8vw,96px);line-height:.88;letter-spacing:-.08em;margin:40px 0 20px}}.lede{{max-width:880px;font-size:20px;color:#cfe4ef}}.panel{{background:rgba(255,255,255,.09);border:1px solid rgba(255,255,255,.2);border-radius:26px;padding:26px;box-shadow:0 25px 80px rgba(0,0,0,.25)}}.grid{{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}}@media(max-width:900px){{.grid{{grid-template-columns:1fr}}}}
</style></head><body><nav><a class="brand" href="./index.html">SkillOS Proof Command Center</a><div><a href="./{SLUG}.html">Latest proof</a> · <a href="https://github.com/MontrealAI/skillos/actions">Run</a></div></nav><main><h1>SkillOS Proof Command Center.</h1><p class="lede">Autonomous, public, reproducible proof pages generated by GitHub Actions.</p>{section}</main></body></html>'''


def section(obj):
    m = obj["metrics"]
    return f'''{MARK_START}
<section id="ai-first-blockchain-capital-machine" class="panel" style="margin:34px 0;background:linear-gradient(140deg,rgba(131,247,255,.16),rgba(166,140,255,.18));">
  <div style="display:flex;justify-content:space-between;gap:20px;align-items:flex-start;flex-wrap:wrap">
    <div style="max-width:760px">
      <div style="color:#83f7ff;font-size:12px;font-weight:950;letter-spacing:.24em;text-transform:uppercase">Flagship autonomous RSI proof</div>
      <h2 style="font-size:clamp(36px,5vw,70px);line-height:.9;letter-spacing:-.07em;margin:12px 0">{TITLE}</h2>
      <p style="font-size:18px;color:#d8edf7">A large autonomous specialist-agent protocol organization recursively improves blockchain capital coordination across capital, blockspace, validator security, MEV control, liquidity, bridges, oracles, governance, settlement, validation, risk courts, and reinvestment.</p>
      <p style="color:#b9d2df">Public benchmark only: not live protocol revenue, token advice, investment advice, achieved superintelligence, or Kardashev Type II civilization.</p>
      <p><a href="./{SLUG}.html" style="display:inline-block;background:#83f7ff;color:#061420;border-radius:999px;padding:12px 18px;font-weight:950">Open proof page</a> <a href="https://github.com/{m.get('github_repository','MontrealAI/skillos')}/actions/workflows/autonomous-rsi-ai-first-blockchain-capital-machine-proof.yml" style="display:inline-block;border:1px solid rgba(255,255,255,.25);border-radius:999px;padding:12px 18px;font-weight:950;color:white">Run on GitHub</a></p>
    </div>
    <div class="grid" style="min-width:min(100%,520px);flex:1">
      <div class="panel" style="padding:18px"><b style="font-size:28px;color:#74ffb4">{m['virtual_specialist_agents']:,}</b><br/><span>agents</span></div>
      <div class="panel" style="padding:18px"><b style="font-size:28px;color:#74ffb4">{m['specialist_roles']:,}</b><br/><span>roles</span></div>
      <div class="panel" style="padding:18px"><b style="font-size:28px;color:#74ffb4">{pct(m['holdout_value_capture'])}</b><br/><span>holdout capture</span></div>
      <div class="panel" style="padding:18px"><b style="font-size:28px;color:#74ffb4">{money(m['value_over_no_rsi_protocol_organization'])}</b><br/><span>over no-RSI</span></div>
    </div>
  </div>
</section>
{MARK_END}'''


def main():
    site = ROOT / "site"
    site.mkdir(exist_ok=True)
    obj = json.loads((ROOT / "data" / f"{SLUG}.json").read_text())
    sec = section(obj)
    idx = site / "index.html"
    if idx.exists():
        text = idx.read_text()
        if MARK_START in text and MARK_END in text:
            text = re.sub(re.escape(MARK_START) + r".*?" + re.escape(MARK_END), sec, text, flags=re.S)
        elif "<main" in text:
            m = re.search(r"<main[^>]*>", text, flags=re.I)
            text = text[:m.end()] + sec + text[m.end():]
        elif "<body" in text:
            m = re.search(r"<body[^>]*>", text, flags=re.I)
            text = text[:m.end()] + sec + text[m.end():]
        else:
            text += sec
    else:
        text = default_index(sec)
    idx.write_text(text)
    registry_path = site / "proof-registry.json"
    if registry_path.exists():
        try:
            registry = json.loads(registry_path.read_text())
            if not isinstance(registry, list): registry = registry.get("proofs", [])
        except Exception:
            registry = []
    else:
        registry = []
    entry = {
        "slug": SLUG,
        "title": PROOF_NAME,
        "href": f"./{SLUG}.html",
        "status": "passing" if obj["metrics"]["proved"] else "failing",
        "agents": obj["metrics"]["virtual_specialist_agents"],
        "roles": obj["metrics"]["specialist_roles"],
        "holdout_value_capture": obj["metrics"]["holdout_value_capture"],
        "updated_at": obj["metrics"]["run_timestamp_utc"],
        "workflow": ".github/workflows/autonomous-rsi-ai-first-blockchain-capital-machine-proof.yml",
    }
    registry = [p for p in registry if p.get("slug") != SLUG]
    registry.insert(0, entry)
    registry_path.write_text(json.dumps(registry, indent=2, sort_keys=True))
    base = "https://montrealai.github.io/skillos"
    urls = ["/", f"/{SLUG}.html"] + [f"/{p.get('href','').replace('./','')}" for p in registry if p.get("href")]
    urls = sorted(set(u for u in urls if u and not u.startswith('/http')))
    (site / "sitemap.xml").write_text("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n" + "\n".join(f"  <url><loc>{base}{u}</loc></url>" for u in urls) + "\n</urlset>\n")
    (site / "robots.txt").write_text(f"User-agent: *\nAllow: /\nSitemap: {base}/sitemap.xml\n")
    print(json.dumps({"published": True, "index": "site/index.html", "proof": f"site/{SLUG}.html"}, indent=2))

if __name__ == "__main__":
    main()
