#!/usr/bin/env python3
"""Validate chamber signature completeness against the frozen v0.1 protocol."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import pandas as pd

REQUIRED_NUMERIC = [
    "struc_i_mean_Ak", "struc_i_min_Ak_mean", "struc_i_Ak_kmax_mean",
    "struc_i_mean_rho", "struc_i_max_rho_mean", "struc_i_rho_kmax_mean",
    "perc_giant_ratio", "perc_isolated_fraction", "perc_chain_span",
    "perc_edge_density_kmax", "perc_outlier_fraction", "perc_tail_dominance",
]


def parse_args() -> argparse.Namespace:
    root = Path(__file__).resolve().parents[1]
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--signatures", type=Path, default=root / "signatures/chamber_signatures.csv")
    p.add_argument("--expected-repeats", type=int, default=5)
    p.add_argument("--allow-incomplete", action="store_true")
    return p.parse_args()


def main() -> int:
    args = parse_args()
    frame = pd.read_csv(args.signatures)
    if frame.empty:
        print("FAIL: signature table is empty; run the chambers and signature builder", file=sys.stderr)
        return 2
    errors = []
    for row in frame.itertuples(index=False):
        gid = row.galaxy_id
        if int(row.struc_i_repeat_count) != args.expected_repeats:
            errors.append(f"{gid}: STRUC-I repeat count {row.struc_i_repeat_count}, expected {args.expected_repeats}")
        if getattr(row, "struc_i_regime", None) in (None, "") or pd.isna(getattr(row, "struc_i_regime", None)):
            errors.append(f"{gid}: missing STRUC-I regime")
        if getattr(row, "perc_source_level", None) != "FULL_DATASET":
            errors.append(f"{gid}: STRUC-PERC source level is {getattr(row, 'perc_source_level', None)}, expected FULL_DATASET")
        if getattr(row, "perc_run_status", None) != "COMPLETE":
            errors.append(f"{gid}: STRUC-PERC run status is {getattr(row, 'perc_run_status', None)}")
        if bool(getattr(row, "perc_approximate_mode", False)):
            errors.append(f"{gid}: STRUC-PERC approximate/downsampled mode")
        for col in REQUIRED_NUMERIC:
            value = getattr(row, col, None)
            if value is None or pd.isna(value):
                errors.append(f"{gid}: missing {col}")
    if errors and not args.allow_incomplete:
        print("CHAMBER EXPORT VALIDATION FAILED", file=sys.stderr)
        print("\n".join(errors[:100]), file=sys.stderr)
        return 2
    if errors:
        print("INCOMPLETE (allowed):")
        print("\n".join(errors[:100]))
    else:
        print(f"PASS: {len(frame)} galaxies have complete canonical chamber signatures")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
