#!/usr/bin/env python3
from __future__ import annotations

import argparse
import sys
from pathlib import Path

import joblib
import numpy as np
import torch

from suite21_data import discover_faculties, selected_history_indices


def main():
    root = "/root/disk_3tb/earlywarning/30072026"
    p = argparse.ArgumentParser()
    p.add_argument("--cache_dir", default=f"{root}/results/cross_faculty_residual_moe/cache")
    p.add_argument("--structured_cache_dir", default=f"{root}/results/suite12_structured_cache")
    p.add_argument("--fold", type=int, default=1)
    args = p.parse_args()

    print("=" * 110)
    print("SUITE21 ENVIRONMENT / CACHE CONTRACT CHECK")
    print("=" * 110)
    print(f"Python: {sys.version.split()[0]}")
    print(f"PyTorch: {torch.__version__}")
    print(f"CUDA available: {torch.cuda.is_available()}")
    if torch.cuda.is_available():
        print(f"CUDA device: {torch.cuda.get_device_name(0)}")

    cache = Path(args.cache_dir)
    structured = Path(args.structured_cache_dir)
    if not cache.exists():
        raise FileNotFoundError(cache)
    if not structured.exists():
        raise FileNotFoundError(structured)
    faculties = discover_faculties(cache, args.fold)
    if not faculties:
        raise RuntimeError(f"No faculties discovered for fold {args.fold}")
    print(f"Faculties discovered: {len(faculties)}")

    common = None
    committee_k = None
    checked = []
    for faculty in faculties:
        cp = cache / f"{faculty}_fold_{args.fold}.joblib"
        sp = structured / f"{faculty}_fold_{args.fold}.joblib"
        if not sp.exists():
            raise FileNotFoundError(sp)
        d = joblib.load(cp)
        s = joblib.load(sp)
        required = [
            "Xtr", "Xte", "ytr", "yte", "feature_names", "cf_covered_mask",
            "cf_probabilities", "pte", "train_frame", "test_frame",
        ]
        missing = [k for k in required if k not in d]
        if missing:
            raise KeyError(f"{faculty}: canonical cache missing {missing}")
        if "train_row_index" not in s or "train" not in s or "target" not in s:
            raise KeyError(f"{faculty}: structured cache missing train_row_index/train/target")
        for split in ["train", "target"]:
            if "student_seq" not in s[split] or "student_mask" not in s[split] or "course_target" not in s[split]:
                raise KeyError(f"{faculty}: structured {split} missing temporal tensors")
        idx = np.asarray(s["train_row_index"], int)
        expected = selected_history_indices(d)
        if not np.array_equal(idx, expected):
            raise RuntimeError(f"{faculty}: structured history row alignment mismatch")
        hp = np.asarray(d["cf_probabilities"])
        tp = np.asarray(d["pte"])
        if hp.ndim != 2 or tp.ndim != 2 or hp.shape[1] != tp.shape[1]:
            raise RuntimeError(f"{faculty}: committee component shape mismatch {hp.shape} vs {tp.shape}")
        if committee_k is None:
            committee_k = hp.shape[1]
        elif committee_k != hp.shape[1]:
            raise RuntimeError(f"{faculty}: committee member count differs")
        names = set(d["feature_names"])
        common = names if common is None else common & names
        checked.append((faculty, len(idx), len(d["yte"]), s["train"]["student_seq"].shape, s["target"]["student_seq"].shape))

    if not common:
        raise RuntimeError("No common raw feature schema")
    print(f"Common raw features: {len(common)}")
    print(f"Committee components: {committee_k}")
    print("First faculties:")
    for row in checked[:5]:
        print(f"  {row[0]} history={row[1]:,} target={row[2]:,} student_seq={row[3]} -> {row[4]}")
    print("[OK] Suite21 cache contract is satisfied.")


if __name__ == "__main__":
    main()
