#!/usr/bin/env python3
"""
Read-only 1S1L regression check for roman_microlensing_data CSV.

This validates a clean PSPL/1S1L + linear source/blend implementation against
the supplied truth and noisy observed curve. It does not touch Git, RMDC26
parquets, or microlens-submit.
"""

from __future__ import annotations

import argparse
import json
import numpy as np
import pandas as pd
from scipy.optimize import least_squares


def magnification(t, t0, u0, te):
    tau = (t - t0) / te
    u = np.sqrt(u0 * u0 + tau * tau)
    return (u * u + 2.0) / (u * np.sqrt(u * u + 4.0))


def solve_linear_flux(A, y, sigma):
    w = 1.0 / np.square(sigma)
    X = np.column_stack([A, np.ones_like(A)])
    normal = X.T @ (w[:, None] * X)
    rhs = X.T @ (w * y)
    fs, fb = np.linalg.solve(normal, rhs)
    return float(fs), float(fb), fs * A + fb


def fit_curve(t, y, sigma):
    t0_guess = float(t[np.argmax(y)])

    def residual(theta):
        t0, log_u0, log_te = theta
        u0 = np.exp(log_u0)
        te = np.exp(log_te)
        A = magnification(t, t0, u0, te)
        _fs, _fb, model = solve_linear_flux(A, y, sigma)
        return (y - model) / sigma

    result = least_squares(
        residual,
        x0=[t0_guess, np.log(0.12), np.log(11.5)],
        bounds=(
            [float(t.min()), np.log(1e-4), np.log(0.02)],
            [float(t.max()), np.log(3.0), np.log(500.0)],
        ),
        max_nfev=3000,
        xtol=1e-13,
        ftol=1e-13,
        gtol=1e-13,
    )

    t0, log_u0, log_te = result.x
    u0 = float(np.exp(log_u0))
    te = float(np.exp(log_te))
    A = magnification(t, float(t0), u0, te)
    fs, fb, model = solve_linear_flux(A, y, sigma)
    z = (y - model) / sigma
    dof = max(len(y) - 5, 1)

    return {
        "t0": float(t0),
        "u0": u0,
        "tE": te,
        "Fs": fs,
        "Fb": fb,
        "chi2": float(np.dot(z, z)),
        "reduced_chi2": float(np.dot(z, z) / dof),
        "residual_mean": float(np.mean(z)),
        "residual_std": float(np.std(z, ddof=1)),
        "p99_abs_residual": float(np.quantile(np.abs(z), 0.99)),
        "max_abs_residual": float(np.max(np.abs(z))),
        "fraction_abs_ge_5": float(np.mean(np.abs(z) >= 5.0)),
        "optimizer_success": bool(result.success),
    }


def main():
    p = argparse.ArgumentParser()
    p.add_argument("csv")
    args = p.parse_args()

    df = pd.read_csv(args.csv)
    required = {
        "julian_date",
        "observed_normalized_flux",
        "flux_uncertainty",
        "true_normalized_flux",
        "fitted_normalized_flux",
        "normalized_residual",
    }
    missing = sorted(required - set(df.columns))
    if missing:
        raise SystemExit(f"Missing columns: {missing}")

    t = df["julian_date"].to_numpy(float)
    sigma = df["flux_uncertainty"].to_numpy(float)

    truth_fit = fit_curve(t, df["true_normalized_flux"].to_numpy(float), sigma)
    observed_fit = fit_curve(t, df["observed_normalized_flux"].to_numpy(float), sigma)

    expected_truth = {
        "t0": 2461898.700,
        "u0": 0.120,
        "tE": 11.500,
        "Fs": 0.820,
        "Fb": 0.180,
    }

    checks = {
        "truth_t0": abs(truth_fit["t0"] - expected_truth["t0"]) < 1e-3,
        "truth_u0": abs(truth_fit["u0"] - expected_truth["u0"]) < 1e-4,
        "truth_tE": abs(truth_fit["tE"] - expected_truth["tE"]) < 1e-3,
        "truth_Fs": abs(truth_fit["Fs"] - expected_truth["Fs"]) < 1e-4,
        "truth_Fb": abs(truth_fit["Fb"] - expected_truth["Fb"]) < 1e-4,
        "observed_fit_reasonable": observed_fit["reduced_chi2"] < 1.10,
        "observed_no_5sigma_tail": observed_fit["fraction_abs_ge_5"] == 0.0,
    }

    output = {
        "rows": int(len(df)),
        "time_span_days": float(t.max() - t.min()),
        "median_cadence_minutes": float(np.median(np.diff(t)) * 1440.0),
        "truth_fit": truth_fit,
        "observed_fit": observed_fit,
        "checks": checks,
        "pass": all(checks.values()),
    }

    print(json.dumps(output, indent=2))
    raise SystemExit(0 if output["pass"] else 2)


if __name__ == "__main__":
    main()
