import sys
import unittest
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import attention_numpy as an  # noqa: E402


class NumpyTransformerTests(unittest.TestCase):
    def setUp(self):
        self.rng = np.random.default_rng(0)

    def test_softmax_rows_sum_to_one_and_stable(self):
        p = an.softmax(np.array([[1000.0, 1000.0, -1000.0]]))
        self.assertTrue(np.allclose(p, [[0.5, 0.5, 0.0]]))

    def test_layer_norm_statistics(self):
        y = an.layer_norm(self.rng.normal(3, 5, size=(4, 16)), np.ones(16))
        self.assertTrue(np.allclose(y.mean(-1), 0, atol=1e-6))
        self.assertTrue(np.allclose(y.std(-1), 1, atol=1e-3))

    def test_gelu_known_values(self):
        self.assertAlmostEqual(float(an.gelu(np.array([0.0]))[0]), 0.0)
        self.assertAlmostEqual(float(an.gelu(np.array([1.0]))[0]), 0.841345, places=5)

    def test_attention_is_causal(self):
        T, C = 6, 8
        W = [self.rng.normal(size=(C, 4)) for _ in range(3)]
        x = self.rng.normal(size=(T, C))
        out1, w = an.attention_head(x, *W)
        self.assertTrue(np.allclose(np.triu(w, 1), 0))
        self.assertTrue(np.allclose(w.sum(-1), 1))
        x2 = x.copy()
        x2[4:] = self.rng.normal(size=(2, C))           # change only the future
        out2, _ = an.attention_head(x2, *W)
        self.assertTrue(np.allclose(out1[:4], out2[:4]))  # the past is unaffected
        self.assertFalse(np.allclose(out1[4:], out2[4:]))

    def test_first_token_attends_only_to_itself(self):
        x = self.rng.normal(size=(3, 4))
        _, w = an.attention_head(x, np.eye(4), np.eye(4), np.eye(4))
        self.assertEqual(w[0, 0], 1.0)

    def test_vectorized_multi_head_equals_loop_over_heads(self):
        T, C, H = 5, 12, 3
        hs = C // H
        x = self.rng.normal(size=(T, C))
        Wqkv = self.rng.normal(size=(C, 3 * C))
        Wproj = np.eye(C)
        fast = an.multi_head_attention(x, Wqkv, Wproj, H)
        Wq, Wk, Wv = np.split(Wqkv, 3, axis=1)
        heads = [an.attention_head(x, Wq[:, h * hs:(h + 1) * hs], Wk[:, h * hs:(h + 1) * hs],
                                   Wv[:, h * hs:(h + 1) * hs])[0] for h in range(H)]
        self.assertTrue(np.allclose(fast, np.concatenate(heads, axis=-1)))

    def test_block_keeps_shape_and_is_causal(self):
        T, C, H = 7, 16, 4
        p = an.init_block(C, self.rng)
        x = self.rng.normal(size=(T, C))
        y = an.block(x, p, H)
        self.assertEqual(y.shape, (T, C))
        x2 = x.copy()
        x2[-1] += 10
        self.assertTrue(np.allclose(y[:-1], an.block(x2, p, H)[:-1]))

    def test_uniform_prediction_loss_is_log_vocab(self):
        loss = an.cross_entropy(np.zeros((10, 65)), np.arange(10))
        self.assertAlmostEqual(loss, np.log(65), places=6)


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