import pandas as pd

from .preprocessing import preprocess_dataframe
from .ridge_model import fit_ridge_model
from .simulate import apply_simulation
from .explain import explain_kpi_model
from .utils import tipo_variable


def run_kpi_analysis(
    df: pd.DataFrame,
    target: str,
    incremento: float,
    top_n: int = 5,
    save_prefix: str = None
):
    """
    Ejecuta pipeline completo:
    1. Preprocesamiento
    2. Ridge Regression
    3. Simulación
    4. Explicabilidad

    Retorna un dict con todos los resultados.
    """

    # 1. Preprocesar
    df_proc = preprocess_dataframe(df)
    df_num = df_proc.select_dtypes(include="number")

    if target not in df_num.columns:
        raise ValueError(f"El target '{target}' no existe en el DataFrame procesado.")

    X = df_num.drop(columns=[target])
    y = df_num[target]

    # 2. RidgeCV
    res_ridge = fit_ridge_model(X, y)
    coefs = res_ridge["coefs"]

    # 3. Simulación
    sim = apply_simulation(
        coef_series=coefs,
        df_mes=df_num,
        target=target,
        incremento_pts=incremento,
        tipo_variable_func=tipo_variable
    )

    # 4. Explicabilidad
    exp = explain_kpi_model(
        X=X,
        y=y,
        coef_series=coefs,
        top=top_n
    )

    # Guardar si es necesario
    if save_prefix:
        exp.to_csv(f"{save_prefix}_explain.csv", index=False)
        sim["candidates"].to_csv(f"{save_prefix}_simulation.csv", index=False)
        coefs.to_csv(f"{save_prefix}_coefs.csv")

    return {
        "ridge": res_ridge,
        "simulation": sim,
        "explain": exp
    }



