"""Replay a trusted checkpoint from raw engineered features and audited prefixes."""
from pathlib import Path
import numpy as np
import joblib
from .data import SequenceStore


def predict_checkpoint(path,rows,corpus,device='cpu'):
    import torch
    from .runner import encode,shuffle_semesters,history_keys
    from .training import predict_neural
    path=Path(path)
    a=joblib.load(path) if path.suffix=='.joblib' else torch.load(path,map_location=device,weights_only=False)
    cfg=a['config'];arm=a['arm'];x=a['preprocessor'].transform(rows[a['features']].to_numpy(float))
    b=None;store=SequenceStore(corpus,a.get('vocab') or {},cfg.get('max_semesters',16),cfg.get('max_courses',32))
    if a.get('vocab') is not None:
        b,_=store.for_rows(rows)
    if arm=='H1':
        summary,names=store.summaries(rows)
        if names!=a['summary_names']:raise ValueError('History summary schema changed')
        x=np.c_[x,summary]
    if arm in ('H2','HR','HS'):
        if arm=='HS':b=shuffle_semesters(b,a['seed'],history_keys(rows))
        x=np.c_[x,encode(a['encoder'],b,device,cfg['batch_size'])]
    return a['model'].predict_proba(x)[:,1] if arm.startswith('H') else predict_neural(a['model'],x,b,device,cfg.get('batch_size',256))
