"""Hand-checked tests for faculty priors and supported same-term origins."""
from __future__ import annotations

from dataclasses import replace
import unittest

import numpy as np

import data as md
try:
    import protocol as pr
except ModuleNotFoundError as exc:
    if exc.name != 'protocol':
        raise
    pr = None


def table(semesters, faculties=None, labels=None, grades=None, names=('A', 'B')):
    n = len(semesters)
    return md.Table(
        x=np.zeros((n, 2)), course_meta=np.full((n, 17), np.nan),
        y=np.zeros(n, int) if labels is None else np.asarray(labels),
        grade=np.full(n, np.nan) if grades is None else np.asarray(grades),
        semester=np.asarray(semesters),
        student=np.asarray([f's{i}' for i in range(n)]),
        course=np.asarray(['c'] * n),
        faculty=np.zeros(n, int) if faculties is None else np.asarray(faculties),
        sample_id=np.asarray([f'row{i}' for i in range(n)]), committee=np.full(n, np.nan),
        faculty_names=names, feature_names=('a', 'b'))


def supported(semesters=range(10), omit=()):
    sem, fac, y = [], [], []
    for s in semesters:
        for f in range(2):
            if (s, f) in omit:
                continue
            sem.extend([s] * 4)
            fac.extend([f] * 4)
            y.extend([1, 0, 0, 0])
    return table(sem, fac, y)


class ProtocolTests(unittest.TestCase):
    def setUp(self):
        self.assertIsNotNone(pr, 'protocol module is not implemented')

    def choose(self, history, target=12, **kwargs):
        options = dict(n_origins=2, min_rows=4, min_faculty_rows=4,
                       min_positive=1, min_negative=1, min_train_rows=8, coverage=1.)
        options.update(kwargs)
        return pr.choose_origins(history, target, **options)

    def test_origin_cohort_minimum_is_global_while_faculty_minimum_is_per_cell(self):
        # At semester 3 the cohort has 24 rows, 12 per faculty. Each faculty
        # has four previous training rows, so both cell and train support pass.
        history = table([0] * 8 + [3] * 24,
                        [0] * 4 + [1] * 4 + [0] * 12 + [1] * 12,
                        [1, 0, 0, 0] * 2 + [1, 0, 0, 0] * 6)
        origins, audit = self.choose(history, target=6, min_rows=20, min_faculty_rows=4)
        self.assertEqual(origins, [3])
        cohort = audit.loc[audit.semester == 3]
        self.assertEqual(cohort.rows.tolist(), [12, 12])
        self.assertTrue((cohort.origin_rows == 24).all())
        self.assertTrue(cohort.eligible.all())
        self.assertTrue(cohort.origin_eligible.all())

    def test_origin_cohort_below_global_minimum_rejects_supported_faculty_cells(self):
        history = table([0] * 8 + [3] * 24,
                        [0] * 4 + [1] * 4 + [0] * 12 + [1] * 12,
                        [1, 0, 0, 0] * 2 + [1, 0, 0, 0] * 6)
        with self.assertRaises(pr.UnsupportedOriginsError) as caught:
            self.choose(history, target=6, min_rows=25, min_faculty_rows=4)
        cohort = caught.exception.audit.loc[caught.exception.audit.semester == 3]
        self.assertTrue((cohort.origin_rows == 24).all())
        self.assertTrue(cohort.eligible.all())
        self.assertFalse(cohort.origin_eligible.any())
        self.assertTrue(cohort.reason.str.contains('origin_rows<25', regex=False).all())

    def test_validation_faculty_minimum_is_independent_of_global_minimum(self):
        # A globally large cohort cannot cover an undersupported faculty cell.
        history = table([0] * 8 + [3] * 26,
                        [0] * 4 + [1] * 4 + [0] * 24 + [1] * 2,
                        [1, 0, 0, 0] * 2 + [1, 0, 0, 0] * 6 + [1, 0])
        with self.assertRaises(pr.UnsupportedOriginsError) as caught:
            self.choose(history, target=6, min_rows=20, min_faculty_rows=4)
        row = caught.exception.audit.loc[(caught.exception.audit.semester == 3) &
                                         (caught.exception.audit.faculty == 'B')].iloc[0]
        self.assertFalse(row.eligible)
        self.assertIn('faculty_rows<4', row.reason)

    def test_faculty_weights_balance_observed_faculties_and_mean_one(self):
        history = table([1] * 6, faculties=[0, 0, 0, 0, 1, 1], labels=[1, 0, 0, 0, 1, 1])
        weights = pr.faculty_weights(history)
        np.testing.assert_allclose(weights, [.75, .75, .75, .75, 1.5, 1.5])
        self.assertAlmostEqual(float(weights.mean()), 1.)
        self.assertAlmostEqual(float(weights[:4].sum()), float(weights[4:].sum()))
        np.testing.assert_array_equal(weights, pr.faculty_weights(replace(history, y=1-history.y)))
        np.testing.assert_array_equal(pr.faculty_weights(history.subset([0, 1])), [1., 1.])
        self.assertEqual(pr.faculty_weights(history.subset([])).shape, (0,))

    def test_prior_evidence_is_cumulative_strict_and_uses_missing_grade_fallback(self):
        # Intentionally unsorted; faculty A at sem 3 sees exactly sem 1/2.
        bank = table([3, 1, 2, 2, 4], [0, 0, 0, 1, 0],
                     [1, 1, 0, 0, 0], [2., 4., np.nan, 8., 9.])
        query = table([3, 4, 2, 3, 1], [0, 0, 1, 1, 0], [0, 1, 0, 1, 1])
        result = pr.prior_evidence(bank, query)
        np.testing.assert_allclose(result, [[.5, .7], [2/3, 1.6/3], [.1, .65], [0., .8], [.1, .65]], atol=1e-7)
        self.assertEqual(result.dtype, np.float32)
        changed_query = replace(query, y=1-query.y)
        np.testing.assert_array_equal(result, pr.prior_evidence(bank, changed_query))
        changed_later = replace(bank, y=np.array([0, 1, 0, 0, 1]), grade=np.array([9., 4., np.nan, 8., 2.]))
        np.testing.assert_array_equal(result[0], pr.prior_evidence(changed_later, query)[0])
        # Earlier outcomes must affect the prior: it cannot be a frozen constant.
        changed_earlier = replace(bank, y=np.array([1, 0, 0, 0, 0]), grade=np.array([2., 8., np.nan, 8., 9.]))
        np.testing.assert_allclose(pr.prior_evidence(changed_earlier, query)[0], [0., .9])

    def test_prior_embargo_and_empty_bank(self):
        bank = table([1, 2, 3], labels=[1, 0, 1], grades=[2., 8., np.nan])
        query = table([4, 3])
        np.testing.assert_allclose(pr.prior_evidence(bank, query, embargo=1), [[.5, .5], [1., .2]])
        np.testing.assert_allclose(pr.prior_evidence(bank.subset([]), query), [[.1, .65], [.1, .65]])
        for value in (-1, .5, float('nan')):
            with self.subTest(embargo=value), self.assertRaises(ValueError):
                pr.prior_evidence(bank, query, embargo=value)
        with self.assertRaisesRegex(ValueError, 'schema'):
            pr.prior_evidence(bank, replace(query, faculty_names=('B', 'A')))

    def test_latest_supported_origins_use_target_term_and_full_audit(self):
        origins, audit = self.choose(supported())
        self.assertEqual(origins, [6, 9])
        self.assertEqual(len(audit), 20)
        self.assertEqual(set(audit.columns), {'semester', 'faculty', 'rows', 'positives', 'negatives',
            'origin_rows', 'train_rows', 'train_faculty_rows', 'same_term', 'eligible', 'reason', 'origin_eligible', 'selected'})
        self.assertEqual(pr.origin_cells(audit, 6), ['A', 'B'])
        self.assertEqual(audit.loc[audit.selected, 'semester'].drop_duplicates().tolist(), [6, 9])
        zero = audit.loc[audit.semester == 0]
        self.assertTrue((zero.train_rows == 0).all())
        self.assertFalse(zero.origin_eligible.any())
        sem8 = audit.loc[(audit.semester == 8) & (audit.faculty == 'A')].iloc[0]
        self.assertEqual(sem8.rows, 4)
        self.assertEqual(sem8.positives, 1)
        self.assertEqual(sem8.negatives, 3)
        self.assertEqual(sem8.train_rows, 64)
        self.assertEqual(sem8.train_faculty_rows, 32)
        self.assertFalse(sem8.same_term)
        self.assertFalse(sem8.origin_eligible)

    def test_missing_faculty_rejects_default_and_explicit_coverage_allows_supported_cell(self):
        history = supported(range(4), omit=((3, 1),))
        with self.assertRaises(pr.UnsupportedOriginsError) as caught:
            self.choose(history, target=6)
        audit = caught.exception.audit
        self.assertEqual(len(audit), 8)
        missing = audit.loc[(audit.semester == 3) & (audit.faculty == 'B')].iloc[0]
        self.assertEqual(missing.rows, 0)
        self.assertFalse(missing.eligible)
        self.assertFalse(audit.selected.any())
        origins, partial = self.choose(history, target=6, coverage=.5)
        self.assertEqual(origins, [3])
        self.assertEqual(pr.origin_cells(partial, 3), ['A'])

    def test_every_eligible_cell_needs_prior_training_faculty_support(self):
        history = supported([0, 3], omit=((0, 1),))
        with self.assertRaises(pr.UnsupportedOriginsError) as caught:
            self.choose(history, target=6, coverage=.5, min_train_rows=4)
        row = caught.exception.audit.loc[(caught.exception.audit.semester == 3) &
                                         (caught.exception.audit.faculty == 'B')].iloc[0]
        self.assertTrue(row.eligible)
        self.assertEqual(row.train_faculty_rows, 0)
        self.assertFalse(row.origin_eligible)
        self.assertIn('train_faculty', row.reason)

    def test_one_class_cells_are_excluded_even_with_zero_thresholds(self):
        history = supported([0, 3])
        labels = history.y.copy()
        labels[(history.semester == 3) & (history.faculty == 1)] = 0
        history = replace(history, y=labels)
        with self.assertRaises(pr.UnsupportedOriginsError) as caught:
            self.choose(history, target=6, min_positive=0, min_negative=0)
        row = caught.exception.audit.loc[(caught.exception.audit.semester == 3) &
                                         (caught.exception.audit.faculty == 'B')].iloc[0]
        self.assertFalse(row.eligible)
        self.assertIn('positive', row.reason)

    def test_same_semester_and_future_origins_never_selected(self):
        origins, audit = self.choose(supported(), target=6)
        self.assertEqual(origins, [3])
        self.assertFalse(audit.loc[audit.semester >= 6, 'origin_eligible'].any())
        self.assertFalse(audit.loc[audit.semester >= 6, 'selected'].any())

    def test_empty_history_has_headered_failure_audit_and_invalid_parameters_reject(self):
        with self.assertRaises(pr.UnsupportedOriginsError) as caught:
            self.choose(table([]))
        self.assertTrue(caught.exception.audit.empty)
        self.assertIn('semester', caught.exception.audit.columns)
        for key, value in [('n_origins', 0), ('n_origins', 1.5), ('min_rows', -1),
                           ('coverage', 0.), ('coverage', 1.1), ('coverage', np.nan)]:
            with self.subTest(parameter=key), self.assertRaises(ValueError):
                self.choose(supported(), **{key: value})
        with self.assertRaises(ValueError):
            self.choose(supported(), target=1.5)


if __name__ == '__main__':
    unittest.main()
