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

from __future__ import annotations

import csv
import subprocess
import sys
from pathlib import Path

BASE = Path(__file__).resolve().parent
REQUIRED = [
    "apld_capex_revenue_series.csv",
    "apld_forecast_accuracy.csv",
    "cross_company_comparison.csv",
    "apld_signal_assessment.csv",
    "apld_one_page_memo.md",
    "strategic5b_loop_summary.csv",
]


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


def main() -> None:
    subprocess.run([sys.executable, "build_apld_capex_revenue_series.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}")
    capex = rows("apld_capex_revenue_series.csv")
    if not any(r["metric"] == "hpc_hosting_revenue" for r in capex):
        raise SystemExit("missing hpc_hosting_revenue")
    if not any(r["metric"] == "property_equipment_investment_increase" for r in capex):
        raise SystemExit("missing capex proxy")
    accuracy = rows("apld_forecast_accuracy.csv")
    if not any(r["overall_score_1_10"] == "10" for r in accuracy):
        raise SystemExit("missing 10/10 forecast hit")
    comparison = rows("cross_company_comparison.csv")
    if {"APLD", "CRWV"} - {r["ticker"] for r in comparison}:
        raise SystemExit("cross-company comparison missing APLD or CRWV")
    signal = rows("apld_signal_assessment.csv")
    overall = [r for r in signal if r["signal_dimension"] == "overall_signal_quality"]
    if not overall or int(overall[0]["score_1_10"]) < 6:
        raise SystemExit("overall signal quality too weak or missing")
    memo = (BASE / "apld_one_page_memo.md").read_text(encoding="utf-8")
    for phrase in ["Next-Quarter Watch Items", "What Would Change", "constructive but execution-dependent"]:
        if phrase not in memo:
            raise SystemExit(f"memo missing {phrase}")
    summary = rows("strategic5b_loop_summary.csv")
    if len(summary) != 5:
        raise SystemExit("expected five loop summaries")
    for row in summary:
        score = int(row["score_1_10"])
        if not 1 <= score <= 10:
            raise SystemExit("score out of range")
        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")
    print("strategic5b APLD validation passed")


if __name__ == "__main__":
    main()
