#!/usr/bin/env python3
"""Build a strategic APLD dashboard from research artifacts."""

from __future__ import annotations

import csv
import html
import subprocess
import sys
from pathlib import Path

BASE = Path(__file__).resolve().parent
OUT = BASE / "strategic_apld_dashboard.html"


def read_csv(name: str) -> list[dict[str, str]]:
    with (BASE / name).open(newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def table(rows: list[dict[str, str]], cols: list[str]) -> str:
    head = "".join(f"<th>{html.escape(c)}</th>" for c in cols)
    body = "".join(
        "<tr>" + "".join(f"<td>{html.escape(row.get(c, ''))}</td>" for c in cols) + "</tr>"
        for row in rows
    )
    return f"<table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table>"


def main() -> None:
    subprocess.run([sys.executable, "score_apld_thesis.py"], cwd=BASE, check=True)
    summary = read_csv("strategic_loop_summary.csv")
    thesis = read_csv("apld_thesis_scores.csv")
    financial = read_csv("apld_financial_conversion_rows.csv")
    status = read_csv("apld_status_table.csv")
    read = (BASE / "apld_research_read.md").read_text(encoding="utf-8")
    page = f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
<title>Strategic APLD Forecast-vs-Actual Dashboard</title>
<style>body{{font-family:system-ui,sans-serif;margin:30px;max-width:1220px;line-height:1.45}}
table{{border-collapse:collapse;width:100%;font-size:13px;margin:14px 0 28px}}td,th{{border:1px solid #ddd;padding:7px;vertical-align:top}}th{{background:#f5f5f5}}
.call{{background:#eef7ff;border-left:4px solid #2670b8;padding:12px 16px}}</style></head><body>
<h1>Strategic APLD Forecast-vs-Actual Dashboard</h1>
<div class="call"><pre>{html.escape(read)}</pre></div>
<h2>Strategic Loop Summary</h2>{table(summary, ["iteration","chose_20_words","did_20_words","score_1_10","score_reason_20_words","next_20_words"])}
<h2>Thesis Scores</h2>{table(thesis, ["hypothesis_id","hypothesis","score_1_10","score_reason","status"])}
<h2>Capacity Status</h2>{table(status, ["project","forecast","actual_or_status","status"])}
<h2>Financial Conversion Rows</h2>{table(financial, ["period_reported","metric","normalized_value","unit","forecast_or_actual","caveat"])}
</body></html>"""
    OUT.write_text(page, encoding="utf-8")
    print(f"wrote {OUT.name}")


if __name__ == "__main__":
    main()
