"""Tests for the Lecture 01 lab.

Learners:   pytest test_lab.py          (or -k core, -k stretch, -k challenge)
Reference:  LAB_MODULE=solutions pytest test_lab.py
"""
import importlib
import os

import numpy as np
import pandas as pd
import pytest
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score as sk_r2
from sklearn.metrics.pairwise import euclidean_distances

lab = importlib.import_module(os.environ.get("LAB_MODULE", "lab"))
rng = np.random.default_rng(0)


def test_core_word_counts():
    assert lab.word_counts("The cat. the CAT, the dog's toy") == {
        "the": 3, "cat": 2, "dog's": 1, "toy": 1,
    }


def test_stretch_top_words_ties_alphabetical():
    counts = {"b": 2, "a": 2, "c": 5, "d": 1}
    assert lab.top_words(counts, 3) == [("c", 5), ("a", 2), ("b", 2)]


def test_core_standardize():
    X = rng.normal(5, 3, size=(100, 4))
    Z = lab.standardize(X)
    np.testing.assert_allclose(Z.mean(axis=0), 0, atol=1e-12)
    np.testing.assert_allclose(Z.std(axis=0), 1, atol=1e-12)


def test_core_standardize_constant_column():
    X = np.column_stack([np.ones(10), np.arange(10.0)])
    Z = lab.standardize(X)
    assert np.all(np.isfinite(Z))
    np.testing.assert_allclose(Z[:, 0], 0)


def test_stretch_pairwise_distances():
    A, B = rng.normal(size=(30, 5)), rng.normal(size=(20, 5))
    D = lab.pairwise_distances(A, B)
    assert D.shape == (30, 20)
    np.testing.assert_allclose(D, euclidean_distances(A, B), atol=1e-10)


def test_stretch_pairwise_distances_self_is_zero():
    A = rng.normal(size=(10, 3)) * 1e3
    np.testing.assert_allclose(np.diag(lab.pairwise_distances(A, A)), 0, atol=1e-4)


def test_challenge_nearest_centroid():
    X = np.array([[0.0, 0.1], [9.8, 10.0], [0.2, -0.1]])
    C = np.array([[0.0, 0.0], [10.0, 10.0]])
    np.testing.assert_array_equal(lab.nearest_centroid(X, C), [0, 1, 0])


@pytest.fixture
def students():
    return pd.DataFrame({
        "track": ["ml", "nlp", "ml", "nlp", "ops"],
        "hours": [10.0, np.nan, 14.0, 8.0, np.nan],
        "score": [70, 85, 90, 77, 60],
    })


def test_stretch_fill_missing(students):
    out = lab.fill_missing(students)
    assert out["hours"].tolist() == [10.0, 10.0, 14.0, 8.0, 10.0]
    assert out["track"].tolist() == students["track"].tolist()
    assert students["hours"].isna().sum() == 2, "input must not be modified"


def test_stretch_group_summary(students):
    out = lab.group_summary(students, "track", "score")
    assert list(out.columns) == ["count", "mean"]
    assert list(out.index) == ["nlp", "ml", "ops"]
    assert out.loc["ml", "mean"] == 80


def test_core_add_intercept():
    Xb = lab.add_intercept(np.arange(6.0).reshape(3, 2))
    np.testing.assert_array_equal(Xb[:, 0], 1)
    assert Xb.shape == (3, 3)


def test_core_least_squares_matches_sklearn():
    X = rng.normal(size=(200, 3))
    y = 2 + X @ np.array([1.5, -3.0, 0.5]) + rng.normal(0, 0.1, 200)
    theta = lab.fit_least_squares(X, y)
    ref = LinearRegression().fit(X, y)
    np.testing.assert_allclose(theta, [ref.intercept_, *ref.coef_], atol=1e-8)
    np.testing.assert_allclose(lab.predict(X, theta), ref.predict(X), atol=1e-8)


def test_stretch_r2_score():
    y = rng.normal(size=50)
    y_hat = y + rng.normal(0, 0.5, 50)
    assert lab.r2_score(y, y_hat) == pytest.approx(sk_r2(y, y_hat))
    assert lab.r2_score(y, np.full(50, y.mean())) == pytest.approx(0)


def test_core_mini_analysis():
    result = lab.analyse_diabetes()
    assert result["r2_bmi"] == pytest.approx(0.3439, abs=1e-3)
    assert result["r2_all"] == pytest.approx(0.5177, abs=1e-3)
    assert result["r2_all"] > result["r2_bmi"]
