import os
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
NAMES = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS',
         'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT']
N_TRAIN = 100


def load_data():
    """First 100 rows = train, remaining 406 rows = test."""
    d = np.loadtxt(os.path.join(HERE, 'housing.data'))
    X = d[:, :13]
    t = d[:, 13]
    return X[:N_TRAIN], t[:N_TRAIN], X[N_TRAIN:], t[N_TRAIN:]


def normalize(Xtr, Xte):
    """z-score using the TRAIN mean and std only, same numbers applied to test."""
    mu = Xtr.mean(axis=0)
    sd = Xtr.std(axis=0)
    if (sd == 0).any():
        print('WARNING: zero std in columns', np.where(sd == 0)[0])
    sd_safe = np.where(sd == 0, 1.0, sd)
    return (Xtr - mu) / sd_safe, (Xte - mu) / sd_safe, mu, sd


def poly_design(X, degree):
    """Columns: bias, then x^1 for every feature, then x^2 for every feature, ...
    Monomials of one variable only, no cross-terms."""
    cols = [np.ones((X.shape[0], 1))]
    for k in range(1, degree + 1):
        cols.append(X ** k)
    return np.hstack(cols)


def fit_ls(Phi, t):
    """Least squares weights (SVD based, safe when Phi is nearly rank deficient)."""
    w, *_ = np.linalg.lstsq(Phi, t, rcond=None)
    return w


def rms(pred, t):
    return np.sqrt(np.mean((pred - t) ** 2))
