"""Lecture 01 lab. Replace each NotImplementedError, then run: pytest test_lab.py

Work in order: core first (pytest -k core), then stretch, then challenge.
AI rule: no AI-generated code for core functions; AI may explain errors and concepts.
"""
import re
from collections import Counter

import numpy as np
import pandas as pd


# Core: everyone completes these


def word_counts(text: str) -> dict[str, int]:
    """Lowercase text, split into words (letters and apostrophes), return {word: count}."""
    raise NotImplementedError


def standardize(X: np.ndarray) -> np.ndarray:
    """Z-score each column of X: subtract column mean, divide by column std. Constant columns: divide by 1. No loops."""
    raise NotImplementedError


def add_intercept(X: np.ndarray) -> np.ndarray:
    """Prepend a column of ones to X."""
    raise NotImplementedError


def fit_least_squares(X: np.ndarray, y: np.ndarray) -> np.ndarray:
    """Return theta = [b, w_1, ..., w_d] minimising ||y - [1 X] theta||^2. Use np.linalg.lstsq."""
    raise NotImplementedError


def predict(X: np.ndarray, theta: np.ndarray) -> np.ndarray:
    """Predictions [1 X] theta."""
    raise NotImplementedError


def analyse_diabetes() -> dict[str, float]:
    """Mini analysis with your core functions: load load_diabetes(as_frame=True, scaled=False).frame,
    fit least squares on BMI alone and on all 10 features, return {"r2_bmi": ..., "r2_all": ...}.
    Compute R^2 = 1 - SS_res / SS_tot inline (r2_score is a stretch function)."""
    raise NotImplementedError


# Stretch: same skills, less scaffolding


def fill_missing(df: pd.DataFrame) -> pd.DataFrame:
    """Fill NaN in numeric columns with that column's median. Leave other columns unchanged. Do not modify the input."""
    raise NotImplementedError


def group_summary(df: pd.DataFrame, by: str, col: str) -> pd.DataFrame:
    """Per group of `by`: count and mean of `col`, columns ["count", "mean"], sorted by mean descending."""
    raise NotImplementedError


def top_words(counts: dict[str, int], k: int) -> list[tuple[str, int]]:
    """Return the k most frequent (word, count) pairs; ties broken alphabetically."""
    raise NotImplementedError


def pairwise_distances(A: np.ndarray, B: np.ndarray) -> np.ndarray:
    """D[i, j] = Euclidean distance between A[i] and B[j]. No loops: derive a broadcastable identity first (notes, section 2)."""
    raise NotImplementedError


def r2_score(y: np.ndarray, y_hat: np.ndarray) -> float:
    """Coefficient of determination: 1 - SS_res / SS_tot."""
    raise NotImplementedError


# Challenge: open-ended, see exercises.md


def nearest_centroid(X: np.ndarray, centroids: np.ndarray) -> np.ndarray:
    """Index of the nearest centroid for each row of X."""
    raise NotImplementedError
