#!/usr/bin/env python3
"""Validate the strategic APLD five-loop research package."""

from __future__ import annotations

import csv
import re
import subprocess
import sys
from pathlib import Path

BASE = Path(__file__).resolve().parent
REQUIRED = [
    "apld_forecast_actual_rows.csv",
    "apld_status_table.csv",
    "apld_forecast_scores.csv",
    "apld_financial_conversion_rows.csv",
    "apld_research_hypotheses.csv",
    "apld_thesis_scores.csv",
    "apld_research_read.md",
    "apld_decision_backlog.csv",
    "strategic_loop_summary.csv",
    "strategic_apld_dashboard.html",
]


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


def snippet_supports(row: dict[str, str]) -> bool:
    snippet = row["source_snippet"].replace(",", "")
    tokens = re.findall(r"\d+(?:\.\d+)?", row["raw_value"].replace(",", ""))
    if bool(tokens) and any(token in snippet for token in tokens):
        return True
    if row.get("unit") == "USD_millions" and "billion" in row["source_snippet"].lower():
        try:
            billion_value = float(row["raw_value"].replace(",", "")) / 1000.0
        except ValueError:
            return False
        return f"{billion_value:g}" in snippet
    return False


def main() -> None:
    subprocess.run([sys.executable, "score_apld_thesis.py"], cwd=BASE, check=True)
    subprocess.run([sys.executable, "build_strategic_apld_dashboard.py"], cwd=BASE, check=True)
    for name in REQUIRED:
        path = BASE / name
        if not path.exists() or path.stat().st_size == 0:
            raise SystemExit(f"missing or empty artifact: {name}")
    financial = rows("apld_financial_conversion_rows.csv")
    if len(financial) < 12:
        raise SystemExit("financial conversion rows too sparse")
    if not any(r["metric"] == "hpc_hosting_revenue" for r in financial):
        raise SystemExit("missing HPC hosting revenue")
    if not any(r["metric"] == "property_equipment_investment_increase" for r in financial):
        raise SystemExit("missing capex proxy")
    for row in financial:
        if not row["source_url"].startswith("https://"):
            raise SystemExit("financial row missing https source")
        if not snippet_supports(row):
            raise SystemExit(f"financial row snippet does not support raw value: {row['metric']} {row['raw_value']}")
    thesis = rows("apld_thesis_scores.csv")
    if len(thesis) != 4:
        raise SystemExit("expected four thesis scores")
    for row in thesis:
        score = int(row["score_1_10"])
        if not 1 <= score <= 10:
            raise SystemExit("thesis score out of range")
    backlog = rows("apld_decision_backlog.csv")
    if len(backlog) < 5:
        raise SystemExit("decision backlog too short")
    summary = rows("strategic_loop_summary.csv")
    if len(summary) != 5:
        raise SystemExit("expected five strategic loop summaries")
    for row in summary:
        for field in ["chose_20_words", "did_20_words", "score_reason_20_words", "next_20_words"]:
            if len(row[field].split()) > 20:
                raise SystemExit(f"{field} exceeds 20 words")
    read = (BASE / "apld_research_read.md").read_text(encoding="utf-8")
    for phrase in ["contracted", "delivered", "revenue", "What Would Change"]:
        if phrase not in read:
            raise SystemExit(f"research read missing {phrase}")
    print("strategic5 APLD validation passed")


if __name__ == "__main__":
    main()
