#!/usr/bin/env python3
"""Fit three OLS models that map six joint readings to end-effector X, Y, Z."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

FEATURES = ["Rev1", "Rev2", "Rev3", "Rev4", "Rev5", "Pris"]
TARGETS = ["X", "Y", "Z"]
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_DATA = ROOT / "data"
DEFAULT_RESULTS = ROOT / "results"

DATA_HELP = """Place traindata1.xlsx and testdata1.xlsx in the data/ folder.
They are not stored in this repository. Copies and links are in data/README.md.
"""


def load_frames(data_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame]:
    train_path = data_dir / "traindata1.xlsx"
    test_path = data_dir / "testdata1.xlsx"
    missing = [p.name for p in (train_path, test_path) if not p.is_file()]
    if missing:
        raise FileNotFoundError(
            "Missing " + ", ".join(missing) + ".\n" + DATA_HELP
        )
    train = pd.read_excel(train_path)
    test = pd.read_excel(test_path)
    needed = FEATURES + TARGETS
    for name, frame in (("train", train), ("test", test)):
        absent = [c for c in needed if c not in frame.columns]
        if absent:
            raise ValueError(f"{name} is missing columns: {absent}")
    return train, test


def fit(train: pd.DataFrame, test: pd.DataFrame) -> dict:
    x_train = train[FEATURES].to_numpy()
    x_test = test[FEATURES].to_numpy()
    out = {}
    for axis in TARGETS:
        model = LinearRegression()
        model.fit(x_train, train[axis].to_numpy())
        pred = model.predict(x_test)
        actual = test[axis].to_numpy()
        mse = float(mean_squared_error(actual, pred))
        out[axis] = {
            "model": model,
            "pred": pred,
            "actual": actual,
            "mse": mse,
            "rmse": float(np.sqrt(mse)),
            "r2": float(r2_score(actual, pred)),
        }
    return out


def print_report(train: pd.DataFrame, test: pd.DataFrame, results: dict) -> None:
    print(f"Train shape : {train.shape}")
    print(f"Test  shape : {test.shape}")
    print(f"Columns     : {train.columns.tolist()}")
    print()
    print("=== Training data statistics ===")
    print(train.describe().round(3).to_string())
    print()
    print("=== Correlation of joints with X, Y, Z ===")
    print(train.corr(numeric_only=True)[TARGETS].round(3).to_string())
    print()
    for axis, row in results.items():
        model = row["model"]
        coefs = {name: round(float(val), 4) for name, val in zip(FEATURES, model.coef_)}
        print(f"{axis} trained | Intercept: {model.intercept_:.4f}")
        print(f"   Coefficients: {coefs}")
        print()
    print("=" * 52)
    print("   MULTIPLE LINEAR REGRESSION — EVALUATION")
    print("=" * 52)
    print(f"  {'Coord':<6}  {'MSE':>10}  {'RMSE':>10}  {'R²':>10}")
    print("-" * 52)
    for axis in TARGETS:
        row = results[axis]
        print(f"  {axis:<6}  {row['mse']:>10.4f}  {row['rmse']:>10.4f}  {row['r2']:>10.4f}")
    print("=" * 52)
    print("  Best predicted: Z  (lowest MSE, highest R²)")
    print()
    print("=" * 60)
    print("  LEARNED EQUATIONS (MLR)")
    print("=" * 60)
    for axis in TARGETS:
        model = results[axis]["model"]
        eq = f"  {axis} = {model.intercept_:.4f}"
        for name, coef in zip(FEATURES, model.coef_):
            sign = "+" if coef >= 0 else "-"
            eq += f" {sign} {abs(coef):.4f}×{name}"
        print(eq)
    print("=" * 60)


def write_outputs(results: dict, test: pd.DataFrame, dest: Path) -> None:
    dest.mkdir(parents=True, exist_ok=True)
    metrics = pd.DataFrame(
        [
            {
                "coord": axis,
                "mse": results[axis]["mse"],
                "rmse": results[axis]["rmse"],
                "r2": results[axis]["r2"],
                "intercept": float(results[axis]["model"].intercept_),
                **{
                    f"coef_{name}": float(val)
                    for name, val in zip(FEATURES, results[axis]["model"].coef_)
                },
            }
            for axis in TARGETS
        ]
    )
    metrics.to_csv(dest / "metrics.csv", index=False, float_format="%.10f")
    lines = []
    for axis in TARGETS:
        model = results[axis]["model"]
        eq = f"{axis} = {model.intercept_:.4f}"
        for name, coef in zip(FEATURES, model.coef_):
            sign = "+" if coef >= 0 else "-"
            eq += f" {sign} {abs(coef):.4f}×{name}"
        lines.append(eq)
    (dest / "equations.txt").write_text("\n".join(lines) + "\n")
    head = pd.DataFrame(
        {
            "X_actual": test["X"].to_numpy()[:10],
            "X_predicted": results["X"]["pred"][:10],
            "Y_actual": test["Y"].to_numpy()[:10],
            "Y_predicted": results["Y"]["pred"][:10],
            "Z_actual": test["Z"].to_numpy()[:10],
            "Z_predicted": results["Z"]["pred"][:10],
        }
    )
    head.index.name = "sample"
    head.to_csv(dest / "predictions_head.csv", float_format="%.4f")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-dir", type=Path, default=DEFAULT_DATA)
    parser.add_argument("--results-dir", type=Path, default=DEFAULT_RESULTS)
    args = parser.parse_args()
    try:
        train, test = load_frames(args.data_dir)
        results = fit(train, test)
        print_report(train, test, results)
        write_outputs(results, test, args.results_dir)
        print(f"\nWrote metrics, equations and the first ten predictions to {args.results_dir}")
    except (OSError, ValueError) as error:
        print(error, file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
