"""Verify and reload a trusted Suite27 checkpoint on its canonical target fold."""
from __future__ import annotations

import argparse
from pathlib import Path

import pandas as pd
import torch

from data import common_feature_names, load_fold
from evaluation import metrics
from experiment import load_bundle
from runtime import atomic_csv, code_hashes, faculty_support, file_hash, json_hash, print_table, score_frame, versions


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--checkpoint', required=True, help='Your own trusted .pt file; contains serialized Python objects')
    p.add_argument('--root', default='/root/disk_3tb/earlywarning/30072026')
    p.add_argument('--cache-dir')
    p.add_argument('--structured-dir')
    p.add_argument('--out-file', required=True)
    p.add_argument('--device', default='cpu')
    p.add_argument('--threads', type=int, default=4)
    args = p.parse_args(argv)
    if Path(args.out_file).exists():
        raise FileExistsError(f'Prediction output already exists: {args.out_file}')
    if args.threads < 1:
        p.error('threads must be positive')
    device = ('cuda' if torch.cuda.is_available() else 'cpu') if args.device == 'auto' else args.device
    selected = torch.device(device)
    if selected.type not in ('cpu', 'cuda') or (selected.type == 'cuda' and not torch.cuda.is_available()):
        p.error('Requested device unsupported or unavailable')
    torch.set_num_threads(args.threads)
    bundle = torch.load(args.checkpoint, map_location='cpu', weights_only=False)
    if bundle.get('format_version') != 1 or 'provenance' not in bundle:
        raise ValueError('Checkpoint lacks the required Suite27 format/provenance')
    provenance = bundle['provenance']
    if provenance['runtime'] != versions():
        raise ValueError('Checkpoint runtime fingerprints differ; use the original Python/package/runtime environment')
    if provenance['code_hashes'] != code_hashes():
        raise ValueError('Checkpoint source code fingerprints differ from this implementation')
    common = provenance['common_features']
    if json_hash(common) != provenance['schema_sha256']:
        raise ValueError('Checkpoint feature-schema fingerprint is corrupt')
    fold, faculties = provenance['fold'], provenance['faculties']
    cache = Path(args.cache_dir or Path(args.root) / 'results/cross_faculty_residual_moe/cache').expanduser().resolve()
    structured = Path(args.structured_dir or Path(args.root) / 'results/suite12_structured_cache').expanduser().resolve()
    for kind, parent in [('cache_dir', cache), ('structured_dir', structured)]:
        for faculty in faculties:
            filename = f'{faculty}_fold_{fold}.joblib'
            prior_path = str(Path(provenance['configuration'][kind]) / filename)
            expected = provenance['input_fingerprints'][prior_path]['sha256']
            if file_hash(parent / filename) != expected:
                raise ValueError(f'Canonical input differs from training: {parent / filename}')
    available = common_feature_names(cache, faculties, fold)
    if any(name not in available for name in common):
        raise ValueError('Canonical feature schema differs from checkpoint')
    history, target, _ = load_fold(cache, structured, faculties, fold, common)
    print_table('Reload target support, every requested faculty', faculty_support(target, faculties))
    _, _, scores = load_bundle(bundle, history, target, device=device)
    column = f"suite27_{bundle['variant']}"
    frame = score_frame(target, fold, {column: scores})
    frame['seed'] = bundle['seed']
    atomic_csv(args.out_file, frame)
    print_table('Reloaded target metrics for every faculty',
                pd.DataFrame([dict(fold=fold, faculty=faculty, variant=bundle['variant'], seed=bundle['seed'],
                                   **metrics(frame.loc[frame.faculty == faculty, 'actual'],
                                             frame.loc[frame.faculty == faculty, column]))
                              for faculty in faculties]))
    print(f'Reloaded {len(frame):,} keyed predictions to {Path(args.out_file).resolve()}', flush=True)
    return frame


if __name__ == '__main__':
    main()
