import numpy as np
import pandas as pd
from sklearn.linear_model import RidgeCV
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import RepeatedKFold

def fit_ridge_model(X: pd.DataFrame, y: pd.Series, alphas=None):
    """
    Entrena un modelo RidgeCV y devuelve:
    - model      : modelo entrenado
    - scaler     : scaler usado
    - coefs      : coeficientes desescalados
    - scores     : CV scores
    """
    if alphas is None:
        alphas = np.logspace(-3, 3, 25)

    rkf = RepeatedKFold(n_splits=5, n_repeats=3, random_state=1)

    scaler = StandardScaler()
    Xs = scaler.fit_transform(X)

    model = RidgeCV(alphas=alphas, cv=rkf, scoring="r2")
    model.fit(Xs, y)

    # Desescalar coeficientes
    coef_unscaled = pd.Series(model.coef_, index=X.columns) / scaler.scale_

    return {
        "model": model,
        "scaler": scaler,
        "coefs": coef_unscaled,
        "scores": model.cv_values_ if hasattr(model, "cv_values_") else None
    }
