import tempfile
import unittest
import numpy as np
import torch
from s34_preprocessing import Preprocessor
from s34_views import bind_manifest, view_indices
from s34_model import IPMVCL
from s34_checkpoint import save_checkpoint, replay_checkpoint
from s34_training import predict_model


class CheckpointTests(unittest.TestCase):
    def test_portable_replay_and_feature_order_guard(self):
        names = ["s", "c", "h"]
        X = np.array([[1, 2, np.nan], [3, 1, 4]], np.float32)
        pp = Preprocessor(names).fit(X)
        m = bind_manifest(names, dict(student=["s"], course=["c"], history=["h"]), pp.bundles)
        cfg = dict(backbone_width=8, residual_blocks=1, view_dim=4, interaction_rank=3, dropout=.1)
        model = IPMVCL(pp.dimension, view_indices(m, pp.bundles), "A2", cfg)
        p = predict_model(model, pp.transform(X))
        result = dict(model=model, preprocessor=pp, manifest=m, selection=dict(selected_epoch=1))
        with tempfile.TemporaryDirectory() as td:
            path = td+"/model.pt"
            save_checkpoint(path, result, dict(seed=29, faculty="synthetic"))
            np.testing.assert_allclose(p, replay_checkpoint(path, X, names), atol=1e-7)
            with self.assertRaisesRegex(ValueError, "schema|order"):
                replay_checkpoint(path, X, names[::-1])
