#!/usr/bin/env python3
"""Verify generated simulator outputs and diagram collateral.

Usage:
  tests/verify_outputs.py out/pcs-scale-both out/usm-scale-both docs/diagrams
"""
from __future__ import annotations

import csv
import json
import sys
from pathlib import Path

REQUIRED = [
    "summary.json",
    "timeline.csv",
    "rdma_packets.csv",
    "openzfs_txg.csv",
    "gpu_kernels.csv",
    "sst_events.csv",
    "sst_components.csv",
    "scaling_decisions.csv",
]


def row_count(path: Path) -> int:
    with path.open(newline="") as f:
        return max(0, sum(1 for _ in f) - 1)


def csv_header(path: Path) -> list[str]:
    with path.open(newline="") as f:
        return next(csv.reader(f))


def verify_output_dir(path: Path, expected_system: str) -> None:
    assert path.is_dir(), f"missing output directory: {path}"
    for name in REQUIRED:
        f = path / name
        assert f.exists(), f"missing {f}"
        assert f.stat().st_size > 0, f"empty {f}"

    summary = json.loads((path / "summary.json").read_text())
    assert summary["system"] == expected_system, summary
    assert summary["requests_total"] > 0, summary
    assert summary["rdma_packets_total"] > 0, summary
    assert summary["scaling_actions"] > 0, summary
    assert summary["roce_p99_us"] > 0, summary
    assert summary["gpu_kernel_p99_us"] >= 0, summary
    assert summary["txg_lag_p99_us"] >= 0, summary
    assert "final_topology" in summary, summary

    assert row_count(path / "timeline.csv") > 10
    assert row_count(path / "rdma_packets.csv") > 10
    assert row_count(path / "openzfs_txg.csv") > 3
    assert row_count(path / "gpu_kernels.csv") > 0
    assert row_count(path / "sst_events.csv") > 10
    assert row_count(path / "sst_components.csv") >= 7
    assert row_count(path / "scaling_decisions.csv") > 0

    rdma_header = csv_header(path / "rdma_packets.csv")
    for col in ["traffic_class", "opcode", "packet_count", "p99_latency_us", "ecn_marks", "cnp_packets", "pfc_pause_us"]:
        assert col in rdma_header, f"{col} missing in rdma_packets.csv"

    txg_text = (path / "openzfs_txg.csv").read_text()
    assert "SYNC_START" in txg_text, "TXG sync never started"
    assert "COMMIT" in txg_text, "TXG commit missing"

    sst_header = csv_header(path / "sst_components.csv")
    assert sst_header == ["component_id", "component_kind", "ports"], sst_header


def verify_diagrams(path: Path) -> None:
    assert path.is_dir(), f"missing diagrams directory: {path}"
    puml_files = sorted((path / "puml").glob("*.puml"))
    assert puml_files, "no PlantUML sources"
    for puml in puml_files:
        png = path / "png" / (puml.stem + ".png")
        svg = path / "svg" / (puml.stem + ".svg")
        assert png.exists() and png.stat().st_size > 0, f"missing rendered PNG for {puml.name}"
        assert svg.exists() and svg.stat().st_size > 0, f"missing rendered SVG for {puml.name}"


def main() -> None:
    if len(sys.argv) != 4:
        raise SystemExit(__doc__)
    verify_output_dir(Path(sys.argv[1]), "pcs")
    verify_output_dir(Path(sys.argv[2]), "usm")
    verify_diagrams(Path(sys.argv[3]))
    print("verify_outputs: ok")


if __name__ == "__main__":
    main()
