import unittest
import tempfile
from pathlib import Path
import pandas as pd
from pace import runner

class RunnerTests(unittest.TestCase):
    def test_selection_uses_only_labels_available_at_origin(self):
        f=pd.DataFrame({'semester':['a','b','c'],'_order':[1,2,3], 'origin_at':pd.to_datetime(['2020-01-01','2020-07-01','2021-01-01'],utc=True), 'label_available_at':pd.to_datetime(['2020-06-01','2020-12-01','2022-01-01'],utc=True),'label':[0,1,0]})
        train,val,refit,v=runner.chronological_split(f,pd.Timestamp('2021-07-01',tz='UTC'))
        self.assertEqual(val.semester.tolist(),['b']);self.assertEqual(train.semester.tolist(),['a']);self.assertEqual(len(refit),2)
    def test_freeze_fingerprint_ignores_output_location_but_not_model(self):
        a={'dim':128,'output_dir':'a','device':'cpu'}
        b={'dim':128,'output_dir':'b','device':'cuda'}
        self.assertEqual(runner.recipe_digest(a),runner.recipe_digest(b))
        b['dim']=64;self.assertNotEqual(runner.recipe_digest(a),runner.recipe_digest(b))
    def test_shuffle_preserves_events_and_is_deterministic(self):
        import numpy as np
        b={'course':np.array([[[3],[4],[5]]]),'semester_mask':np.ones((1,3),bool),'gaps':np.array([[0,1,4]])}
        s=runner.shuffle_semesters(b,29)
        self.assertEqual(sorted(s['course'].ravel().tolist()),[3,4,5]);np.testing.assert_array_equal(s['course'],runner.shuffle_semesters(b,29)['course'])
    def test_cutoff_scope_cache_key_changes_with_final_epoch_budget(self):
        self.assertNotEqual(runner.ssl_key('2020','gru','joint',29,'all',2),runner.ssl_key('2020','gru','joint',29,'all',3))
if __name__=='__main__':unittest.main()

class ResumeTests(unittest.TestCase):
    def test_completed_cell_requires_checkpoint_and_valid_hashes(self):
        import json
        with tempfile.TemporaryDirectory() as td:
            p=Path(td);(p/'complete.json').write_text(json.dumps({'arm':'H0'}))
            pd.DataFrame({'row_id':['r'],'y':[0],'p':[.2]}).to_csv(p/'predictions.csv',index=False)
            with self.assertRaisesRegex(ValueError,'checkpoint|artifact'):
                runner.validate_resume_cell(p,None,None,'cpu')
    def test_source_digest_changes_when_code_changes(self):
        with tempfile.TemporaryDirectory() as td:
            p=Path(td);(p/'x.py').write_text('a=1\n');a=runner.source_digest(p)
            (p/'x.py').write_text('a=2\n');self.assertNotEqual(a,runner.source_digest(p))


class BudgetSelectionTests(unittest.TestCase):
    def test_hgb_uses_recorded_bce_fallback_when_ap_undefined(self):
        import numpy as np
        a,reason=runner.hgb_validation_score(np.zeros(3),np.ones(3)*.1)
        b,_=runner.hgb_validation_score(np.zeros(3),np.ones(3)*.9)
        self.assertGreater(a,b);self.assertIn('BCE',reason)


class ChronologyPlaceboTests(unittest.TestCase):
    def test_indexed_shuffle_keeps_prefix_storage_unique_and_replays_dense(self):
        import numpy as np
        from pace.data import IndexedHistory
        unique={'course':np.arange(8).reshape(2,4,1),'semester_mask':np.ones((2,4),bool),'gaps':np.tile(np.arange(4),(2,1))}
        back=np.array([0,1,0,1]);keys=['s1|t','s2|t','s1|t','s2|t']
        compact=runner.shuffle_semesters(IndexedHistory(unique,back),30,keys)
        dense=runner.shuffle_semesters({k:v[back] for k,v in unique.items()},30,keys)
        self.assertIsInstance(compact,IndexedHistory)
        self.assertEqual(len(compact.unique['course']),2)
        np.testing.assert_array_equal(compact['course'],dense['course'])

    def test_shuffle_follows_student_prefix_identity_across_row_order_and_batching(self):
        import numpy as np
        b={'course':np.arange(12).reshape(3,4,1),'semester_mask':np.ones((3,4),bool),'gaps':np.tile(np.arange(4),(3,1))}
        keys=['s1|t','s2|t','s3|t'];out=runner.shuffle_semesters(b,30,keys)
        p=np.array([2,0,1]);sh=runner.shuffle_semesters({k:v[p] for k,v in b.items()},30,[keys[i] for i in p])
        np.testing.assert_array_equal(out['course'],sh['course'][np.argsort(p)])
        single=runner.shuffle_semesters({k:v[1:2] for k,v in b.items()},30,keys[1:2])
        np.testing.assert_array_equal(out['course'][1:2],single['course'])
