#!/usr/bin/env python3
"""Validate the strategic 10-loop EQIX package using the hardened gates."""

from __future__ import annotations

import csv
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, "/home/dev")

from research_loop.validate import production_gate_failures


BASE = Path(__file__).resolve().parent
RUN = BASE.parent
PUBLIC = RUN / "public" / "index.html"
SERVED = Path("/home/dev/public/research-loop/strategic10-eqix-001/index.html")
REQUIRED = [
    "eqix_source_inventory.csv",
    "eqix_source_fetch_log.csv",
    "eqix_core_evidence_rows.csv",
    "eqix_diagnostics.csv",
    "eqix_signal_scores.csv",
    "eqix_company_role_comparison.csv",
    "eqix_decision_backlog.csv",
    "eqix_one_page_memo.md",
    "strategic10_loop_summary.csv",
    "strategic_eqix_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 require(condition: bool, message: str) -> None:
    if not condition:
        raise SystemExit(message)


def main() -> None:
    subprocess.run([sys.executable, "build_strategic10_eqix.py"], cwd=BASE, check=True)
    for name in REQUIRED:
        path = BASE / name
        require(path.exists() and path.stat().st_size > 0, f"missing or empty artifact: {name}")

    gate = production_gate_failures(RUN, {"run_type": "company_deep_dive", "expected_artifacts": REQUIRED})
    require(not gate, "production gate failures: " + "; ".join(gate))

    evidence = rows("eqix_core_evidence_rows.csv")
    metrics = {r["metric"] for r in evidence}
    for metric in [
        "revenue",
        "annualized_gross_bookings",
        "major_projects",
        "xscale_projects",
        "xscale_capacity_delivered",
        "total_interconnections",
    ]:
        require(metric in metrics, f"missing metric: {metric}")
    require(any(float(r["value"]) >= 474 for r in evidence if r["metric"] == "annualized_gross_bookings"), "missing Q4 bookings value")
    require(any(float(r["value"]) >= 90 for r in evidence if r["metric"] == "xscale_capacity_delivered"), "missing xScale delivered MW")

    summary = rows("strategic10_loop_summary.csv")
    require(len(summary) == 10, "expected ten loop rows")
    for row in summary:
        require(1 <= int(row["score_1_10"]) <= 10, "loop score out of range")
        for field in ["chose_20_words", "did_20_words", "score_reason_20_words", "next_20_words"]:
            require(len(row[field].split()) <= 20, f"{field} exceeds 20 words")

    memo = (BASE / "eqix_one_page_memo.md").read_text(encoding="utf-8")
    for phrase in ["Remaining Gaps", "What Would Change", "Equinix", "APLD", "CRWV", "ORCL"]:
        require(phrase in memo, f"memo missing {phrase}")

    require(PUBLIC.exists() and PUBLIC.stat().st_size > 0, "local public index missing")
    require(SERVED.exists() and SERVED.stat().st_size > 0, "served public index missing")
    page = SERVED.read_text(encoding="utf-8")
    for phrase in ["EQIX Strategic 10-Loop Research", "Core Evidence Ledger", "Signal Scores"]:
        require(phrase in page, f"served page missing {phrase}")

    print("strategic10 EQIX validation passed")


if __name__ == "__main__":
    main()
