import math
import random
import unittest

from mlq import clustering, linear, metrics, neural, trees


class MetricsTest(unittest.TestCase):
    def test_precision_recall_f1(self):
        y_true = [1, 1, 1, 0, 0, 0, 0, 1]
        y_pred = [1, 1, 0, 1, 0, 0, 0, 0]
        p, r, f1 = metrics.precision_recall_f1(y_true, y_pred)
        self.assertAlmostEqual(p, 2 / 3)
        self.assertAlmostEqual(r, 2 / 4)
        self.assertAlmostEqual(f1, 2 * (2 / 3) * 0.5 / (2 / 3 + 0.5))

    def test_auc_matches_pairwise_definition(self):
        rng = random.Random(1)
        y = [rng.randint(0, 1) for _ in range(200)]
        s = [round(rng.random() + 0.3 * t, 2) for t in y]  # rounding creates ties
        pos = [si for si, yi in zip(s, y) if yi]
        neg = [si for si, yi in zip(s, y) if not yi]
        brute = sum((a > b) + 0.5 * (a == b) for a in pos for b in neg) / (len(pos) * len(neg))
        self.assertAlmostEqual(metrics.roc_auc(y, s), brute)
        self.assertEqual(metrics.roc_auc([0, 0, 1, 1], [0.1, 0.2, 0.8, 0.9]), 1.0)

    def test_log_loss_and_regression_metrics(self):
        self.assertAlmostEqual(metrics.log_loss([1, 0], [0.9, 0.1]), -math.log(0.9))
        self.assertTrue(math.isfinite(metrics.log_loss([1], [0.0])))
        self.assertEqual(metrics.mse([1, 2], [1, 4]), 2)
        self.assertEqual(metrics.r2_score([1, 2, 3], [1, 2, 3]), 1)


class LinearModelsTest(unittest.TestCase):
    def test_linear_regression_recovers_line(self):
        X = [[x / 10] for x in range(-20, 21)]
        y = [3 * x[0] + 2 for x in X]
        model = linear.LinearRegression(lr=0.1, epochs=3000).fit(X, y)
        self.assertAlmostEqual(model.w[0], 3, places=3)
        self.assertAlmostEqual(model.b, 2, places=3)

    def test_ridge_shrinks_weights(self):
        X = [[x / 10] for x in range(-20, 21)]
        y = [3 * x[0] for x in X]
        plain = linear.LinearRegression(lr=0.1, epochs=2000).fit(X, y)
        ridge = linear.LinearRegression(lr=0.1, epochs=2000, l2=1.0).fit(X, y)
        self.assertLess(abs(ridge.w[0]), abs(plain.w[0]))

    def test_logistic_regression_separates_classes(self):
        rng = random.Random(0)
        X = [[rng.gauss(-2, 1), rng.gauss(-2, 1)] for _ in range(50)] + \
            [[rng.gauss(2, 1), rng.gauss(2, 1)] for _ in range(50)]
        y = [0] * 50 + [1] * 50
        model = linear.LogisticRegression(lr=0.5, epochs=500).fit(X, y)
        acc = sum(p == t for p, t in zip(model.predict(X), y)) / len(y)
        self.assertGreater(acc, 0.95)

    def test_sigmoid_is_stable(self):
        self.assertEqual(linear.sigmoid(1000), 1.0)
        self.assertEqual(linear.sigmoid(-1000), 0.0)
        self.assertEqual(linear.sigmoid(0), 0.5)


class ClusteringTest(unittest.TestCase):
    def test_kmeans_finds_blobs(self):
        rng = random.Random(3)
        centers = [(0, 0), (10, 10), (0, 10)]
        pts = [[cx + rng.gauss(0, 0.5), cy + rng.gauss(0, 0.5)] for cx, cy in centers for _ in range(30)]
        cents, labels = clustering.kmeans(pts, 3)
        found = sorted((round(x), round(y)) for x, y in cents)
        self.assertEqual(found, sorted(centers))
        self.assertEqual(len(set(labels[:30])), 1)
        self.assertLess(clustering.inertia(pts, cents, labels), 90 * 1.0)

    def test_knn(self):
        X = [[0, 0], [0, 1], [1, 0], [5, 5], [5, 6], [6, 5]]
        y = ["a", "a", "a", "b", "b", "b"]
        self.assertEqual(clustering.knn_predict(X, y, [0.2, 0.3], k=3), "a")
        self.assertEqual(clustering.knn_predict(X, y, [5.5, 5.2], k=3), "b")


class TreesTest(unittest.TestCase):
    def test_impurity(self):
        self.assertEqual(trees.gini([1, 1, 1]), 0)
        self.assertAlmostEqual(trees.gini([0, 1]), 0.5)
        self.assertAlmostEqual(trees.entropy([0, 1]), 1.0)
        self.assertAlmostEqual(trees.information_gain([0, 0, 1, 1], [0, 0], [1, 1]), 1.0)

    def test_best_split(self):
        X = [[1, 7], [2, 3], [3, 9], [10, 1], [11, 8], [12, 2]]
        y = [0, 0, 0, 1, 1, 1]
        f, t, score = trees.best_split(X, y)
        self.assertEqual((f, t, score), (0, 6.5, 0.0))


class NeuralTest(unittest.TestCase):
    def test_softmax_stable_and_normalized(self):
        p = neural.softmax([1000, 1001, 1002])
        self.assertAlmostEqual(sum(p), 1.0)
        self.assertAlmostEqual(p[2] / p[1], math.e)

    def test_cross_entropy_and_gradient(self):
        logits, target = [2.0, 1.0, 0.1], 0
        self.assertAlmostEqual(neural.cross_entropy(logits, target), -math.log(neural.softmax(logits)[0]))
        grad = neural.softmax_cross_entropy_grad(logits, target)
        h = 1e-6  # finite-difference check of the analytic gradient
        for i in range(3):
            bumped = list(logits)
            bumped[i] += h
            numeric = (neural.cross_entropy(bumped, target) - neural.cross_entropy(logits, target)) / h
            self.assertAlmostEqual(grad[i], numeric, places=4)

    def test_attention(self):
        Q = [[1.0, 0.0], [0.0, 1.0]]
        K = [[1.0, 0.0], [0.0, 1.0]]
        V = [[10.0], [20.0]]
        out = neural.scaled_dot_product_attention(Q, K, V)
        self.assertLess(out[0][0], 15)  # query 0 attends more to key 0
        self.assertGreater(out[1][0], 15)
        causal = neural.scaled_dot_product_attention(Q, K, V, causal=True)
        self.assertAlmostEqual(causal[0][0], 10.0)  # first position sees only itself

    def test_dropout_and_batchnorm(self):
        rng = random.Random(0)
        xs = [1.0] * 10000
        out = neural.dropout(xs, 0.5, rng=rng)
        self.assertAlmostEqual(sum(out) / len(out), 1.0, delta=0.05)  # expectation preserved
        self.assertEqual(neural.dropout(xs, 0.5, training=False), xs)
        bn = neural.batch_norm([1.0, 2.0, 3.0, 4.0])
        self.assertAlmostEqual(sum(bn), 0.0)
        self.assertAlmostEqual(sum(x * x for x in bn) / 4, 1.0, places=4)
        self.assertEqual(neural.matmul([[1, 2]], [[3], [4]]), [[11]])


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