"""Reload a trusted Suite26 checkpoint and reproduce its canonical target scores."""
from __future__ import annotations

import argparse
from pathlib import Path
import torch

from mint_data import load_fold, Preprocessor, build_history, MemoryDataset
from mint_model import MemoryIntegratedForest
from mint_runtime import infer, score_frame, sha256


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--checkpoint', required=True)
    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='auto')
    p.add_argument('--batch-size', type=int, default=128)
    p.add_argument('--threads', type=int, default=4)
    p.add_argument('--allow-changed-cache', action='store_true', help='Explicitly allow inference on changed canonical files after training; logs a warning.')
    args = p.parse_args(argv)
    if Path(args.out_file).exists():
        raise FileExistsError(f'Prediction output already exists: {args.out_file}')
    device = 'cuda' if torch.cuda.is_available() else 'cpu' if args.device == 'auto' else args.device
    if args.device != 'auto':
        device = args.device
    torch.set_num_threads(args.threads)
    # Bundles contain NumPy preprocessing state. Only load your own trusted files.
    bundle = torch.load(args.checkpoint, map_location='cpu', weights_only=False)
    cache = Path(args.cache_dir or Path(args.root) / 'results/cross_faculty_residual_moe/cache')
    structured = Path(args.structured_dir or Path(args.root) / 'results/suite12_structured_cache')
    fold, faculties = bundle['fold'], bundle['faculties']
    for kind, parent in [('cache_dir', cache), ('structured_dir', structured)]:
        for faculty in faculties:
            filename = f'{faculty}_fold_{fold}.joblib'
            prior_path = str(Path(bundle['configuration'][kind]) / filename)
            expected = bundle['input_fingerprints'][prior_path]['sha256']
            if sha256(parent / filename) != expected:
                if not args.allow_changed_cache:
                    raise ValueError(f'Input differs from training: {parent / filename}. Use the original cache or explicitly allow a new inference cache.')
                print(f'WARNING: changed inference cache {parent / filename}', flush=True)
    history, target, _ = load_fold(cache, structured, faculties, fold, bundle['common_features'])
    pre = Preprocessor.from_dict(bundle['preprocessor'])
    bank, query = pre.transform(history), pre.transform(target)
    index = build_history(history, target, max_history=bundle['max_history'])
    dataset = MemoryDataset(query, bank, index)
    model = MemoryIntegratedForest(bundle['blueprint'], **bundle['model_config']).to(device)
    model.load_state_dict(bundle['model_state'])
    score, _ = infer(model, dataset, device, args.batch_size)
    frame = score_frame(target, fold)
    frame[f"suite26_{bundle['model_config']['variant']}"] = score
    Path(args.out_file).parent.mkdir(parents=True, exist_ok=True)
    frame.to_csv(args.out_file, index=False)
    print(f'Reloaded {len(frame):,} predictions to {args.out_file}', flush=True)


if __name__ == '__main__':
    main()
