import tempfile
import unittest
from pathlib import Path
import joblib
import numpy as np
from s34_synthetic import make_synthetic
from s34_data import discover_population, inspect_population, load_cell


class DataTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.root = Path(self.tmp.name)
        self.cache, self.structured = make_synthetic(self.root, rows=24)
        self.population = discover_population(self.cache, self.structured, 2)
        self.faculty = sorted(self.population)[0]

    def tearDown(self):
        self.tmp.cleanup()

    def test_common_schema_uses_full_population_and_all_seven_folds(self):
        names, audit, calendar, hashes = inspect_population(self.population)
        self.assertEqual(len(audit), 14)
        self.assertNotIn("native_0", names)
        self.assertEqual(len(calendar), 7)
        self.assertEqual(len(hashes), 28)
        cell = load_cell(*self.population[self.faculty][1], self.faculty, 1, names)
        self.assertEqual(cell.history.X.shape[1], len(names) + 17)
        self.assertEqual(len(cell.target.y), 24)
        self.assertEqual(len(set(cell.target.row_index)), 24)

    def test_shuffled_equal_length_sidecar_is_rejected(self):
        cp, sp = self.population[self.faculty][1]
        sidecar = joblib.load(sp)
        sidecar["train_row_index"] = sidecar["train_row_index"][::-1]
        joblib.dump(sidecar, sp)
        with self.assertRaisesRegex(ValueError, "row.*align|indices"):
            load_cell(cp, sp, self.faculty, 1)

    def test_finite_probability_filter_is_part_of_alignment(self):
        cp, sp = self.population[self.faculty][1]
        cache = joblib.load(cp)
        ix = int(np.flatnonzero(cache["cf_covered_mask"])[0])
        cache["cf_probabilities"][ix, 0] = np.nan
        joblib.dump(cache, cp)
        with self.assertRaisesRegex(ValueError, "row.*align|indices"):
            load_cell(cp, sp, self.faculty, 1)

    def test_invalid_coverage_and_feature_names_fail(self):
        cp, sp = self.population[self.faculty][1]
        cache = joblib.load(cp)
        cache["cf_covered_mask"] = np.ones(3, bool)
        joblib.dump(cache, cp)
        with self.assertRaises(ValueError):
            load_cell(cp, sp, self.faculty, 1)

    def test_missing_fold_is_not_silently_skipped(self):
        self.population[self.faculty][7][0].unlink()
        with self.assertRaisesRegex(ValueError, "fold"):
            discover_population(self.cache, self.structured, 2)

    def test_future_history_fails(self):
        cp, sp = self.population[self.faculty][1]
        cache = joblib.load(cp)
        cache["train_frame"]["target_NHHK"] = cache["test_frame"]["target_NHHK"].iloc[0]
        joblib.dump(cache, cp)
        with self.assertRaisesRegex(ValueError, "chronolog|history"):
            load_cell(cp, sp, self.faculty, 1)
