import unittest
import numpy as np
from s34_preprocessing import Preprocessor
from s34_views import bind_manifest, randomize_manifest, view_indices


class ViewTests(unittest.TestCase):
    def setUp(self):
        self.names = ["s1", "s2", "c1", "c2", "h1", "h2", "other"]
        self.catalog = dict(student=["s1", "s2"], course=["c1", "c2"],
                            history=["h1", "h2"], full_path_only=["other"])

    def test_all_missing_fixed_channels_and_no_target_fitting(self):
        x = np.array([[1, np.nan, 0, 3, 2, 1, 0], [3, np.nan, 0, 5, 2, 1, 0]], float)
        pp = Preprocessor(self.names).fit(x)
        z = pp.transform(np.array([[999, 8, 0, np.inf, 2, 1, 0]], float))
        self.assertEqual(z.shape, (1, 14))
        self.assertTrue(np.isfinite(z).all())
        self.assertEqual(pp.median[0], 2)
        self.assertEqual(z[0, 3 + 7], 1)
        self.assertEqual(pp.bundles["s1"], [0, 7])

    def test_placebo_preserves_bundles_information_and_counts(self):
        pp = Preprocessor(self.names, categorical=["s1"], categorical_slots=3)
        m = bind_manifest(self.names, self.catalog, pp.bundles)
        p = randomize_manifest(m, pp.bundles, 29)
        self.assertEqual(p, randomize_manifest(m, pp.bundles, 29))
        for view in ["student", "course", "history"]:
            self.assertEqual(len(m[view]), len(p[view]))
            self.assertEqual(len(view_indices(m, pp.bundles)[view]),
                             len(view_indices(p, pp.bundles)[view]))
        self.assertEqual(p["full_path_only"], ["other"])
        eligible = sorted(self.names[:-1])
        self.assertEqual(sorted(sum([p[v] for v in ["student", "course", "history"]], [])), eligible)
        for name in eligible:
            owner = next(v for v in ["student", "course", "history"] if name in p[v])
            self.assertTrue(set(pp.bundles[name]).issubset(view_indices(p, pp.bundles)[owner]))

    def test_duplicate_semantic_membership_rejected(self):
        pp = Preprocessor(self.names)
        self.catalog["history"].append("s1")
        with self.assertRaises(ValueError):
            bind_manifest(self.names, self.catalog, pp.bundles)

    def test_categorical_oov_is_explicit_and_dimensions_fixed(self):
        pp = Preprocessor(["code"], categorical=["code"], categorical_slots=3).fit(np.array([[1], [2]]))
        z = pp.transform(np.array([[9], [1], [np.nan]]))
        self.assertEqual(z.shape, (3, 6))
        self.assertEqual(z[0, -1], 1)
        self.assertEqual(z[1, 2], 1)
        self.assertEqual(z[2, 1], 1)
