"""Standardized Lasso with lambda.min / lambda.1se and optional post-selection OLS."""
# ---------------- SETTINGS: edit these before running ----------------
DATA_FILE = "data/quarterlySales.csv"  # Relative to this script, or an absolute path.
DELIMITER = None                     # None = detect; ',' = comma; '\t' = tab.
Y_COLUMN = "Product1"                 # Dependent variable (numeric).
X_COLUMNS = ["Unemp_Pct", "CPI_Pct", "RGDP", "Time", "Q4"]
CATEGORICAL_COLUMNS = []              # Add numeric category codes here, if any.
SORT_BY = "Time"                      # None keeps file order; important for holdouts.
HOLDOUT_COUNT = 0                     # Last N observed Y rows reserved for evaluation.
LAMBDA_CHOICE = "lambda.1se"   # Or "lambda.min" (lowest mean validation MSE).
PREDICTION_MODEL = "Lasso"      # Or "OLS" (unpenalized refit of selected columns).
CV_FOLDS = 10
CV_METHOD = "random"            # "random" resembles Shiny; "time" for forward validation.
RANDOM_SEED = 9
N_LAMBDAS = 100
LAMBDA_MIN = 0.01               # Grid endpoints in Python's alpha / lambda units.
LAMBDA_MAX = 100.0              # Increase if the CV winner is at an endpoint.

from pathlib import Path
import numpy as np
import pandas as pd
from model_tools import (prepare, output_folder, design, fit_model, write_summary,
                         regression_report, stepwise)


def main():
    folder = output_folder(__file__)
    filename = Path(__file__).resolve().parent / DATA_FILE
    data, y, X, groups, train, can_predict, status = prepare(
        filename, DELIMITER, Y_COLUMN, X_COLUMNS, CATEGORICAL_COLUMNS,
        sort_by=SORT_BY, holdout_count=HOLDOUT_COUNT)
    from sklearn.linear_model import Lasso
    from sklearn.preprocessing import StandardScaler
    from sklearn.pipeline import make_pipeline
    from sklearn.model_selection import KFold, TimeSeriesSplit
    from sklearn.metrics import mean_squared_error
    import matplotlib.pyplot as plt
    if LAMBDA_CHOICE not in {"lambda.min", "lambda.1se"} or PREDICTION_MODEL not in {"Lasso", "OLS"}:
        raise ValueError("Check LAMBDA_CHOICE and PREDICTION_MODEL.")
    if not 2 <= CV_FOLDS < train.sum() or N_LAMBDAS < 2 or not 0 < LAMBDA_MIN < LAMBDA_MAX:
        raise ValueError("Check the CV fold count and positive lambda grid endpoints.")
    if X.shape[1] == 0:
        raise ValueError("Lasso needs at least one nonconstant X.")
    xtrain, ytrain = X.loc[train], y.loc[train]
    if CV_METHOD == "random":
        splitter = KFold(CV_FOLDS, shuffle=True, random_state=RANDOM_SEED)
    elif CV_METHOD == "time":
        splitter = TimeSeriesSplit(n_splits=CV_FOLDS)
    else:
        raise ValueError("CV_METHOD must be random or time.")
    folds = list(splitter.split(xtrain))
    lambdas = np.geomspace(LAMBDA_MAX, LAMBDA_MIN, N_LAMBDAS)
    losses = np.empty((N_LAMBDAS, len(folds)))
    # Scaling is fitted inside each fold to avoid using validation data in training.
    for i, lam in enumerate(lambdas):
        for j, (fit_rows, validation_rows) in enumerate(folds):
            pipeline = make_pipeline(StandardScaler(), Lasso(alpha=lam, max_iter=100000, tol=1e-7))
            pipeline.fit(xtrain.iloc[fit_rows], ytrain.iloc[fit_rows])
            losses[i, j] = mean_squared_error(ytrain.iloc[validation_rows], pipeline.predict(xtrain.iloc[validation_rows]))
    mean_loss = losses.mean(axis=1)
    standard_error = losses.std(axis=1, ddof=1) / np.sqrt(len(folds))
    min_index = int(mean_loss.argmin())
    # Grid descends: the first eligible lambda is the LARGEST within one SE.
    one_se_index = int(np.flatnonzero(mean_loss <= mean_loss[min_index] + standard_error[min_index])[0])
    chosen_index = min_index if LAMBDA_CHOICE == "lambda.min" else one_se_index
    chosen_lambda = float(lambdas[chosen_index])
    cv = pd.DataFrame({"lambda": lambdas, "mean_MSE": mean_loss, "SE": standard_error})
    cv.to_csv(folder / "cross_validation.csv", index=False)
    print(f"lambda.min={lambdas[min_index]:.6g}, lambda.1se={lambdas[one_se_index]:.6g}; chosen={chosen_lambda:.6g}")
    if min_index in {0, len(lambdas)-1}:
        print("CV minimum is at a grid endpoint. Consider expanding LAMBDA_MIN/MAX.")
    scaler = StandardScaler().fit(xtrain)
    standardized = scaler.transform(xtrain)
    lasso = Lasso(alpha=chosen_lambda, max_iter=100000, tol=1e-7).fit(standardized, ytrain)
    # Undo X scaling so reported coefficients refer to the original predictor units.
    raw_coef = lasso.coef_ / scaler.scale_
    raw_intercept = lasso.intercept_ - np.dot(raw_coef, scaler.mean_)
    coefficients = pd.Series([raw_intercept, *raw_coef], index=["Intercept", *X.columns])
    coefficients.to_csv(folder / "lasso_coefficients.csv", header=["coefficient"], index_label="term")
    selected_columns = list(X.columns[np.abs(lasso.coef_) > 1e-8])
    print("Selected encoded columns:", selected_columns or "Intercept only")
    summary = f"Chosen lambda: {chosen_lambda}\nCriterion: {LAMBDA_CHOICE}\nPrediction model: {PREDICTION_MODEL}\n" + repr(groups)
    (folder / "model_summary.txt").write_text(summary, encoding="utf-8")
    pd.DataFrame({"criterion":["lambda.min","lambda.1se"],
                  "lambda":[lambdas[min_index],lambdas[one_se_index]]}).to_csv(folder / "lambda_choices.csv",index=False)
    # Plot the coefficient shrinkage paths and the cross-validation curve.
    path = []
    for lam in lambdas:
        fit = Lasso(alpha=lam, max_iter=100000, tol=1e-7).fit(standardized, ytrain)
        path.append(fit.coef_ / scaler.scale_)
    fig, axes = plt.subplots(1, 2, figsize=(13, 5))
    for j, column in enumerate(X.columns):
        axes[0].plot(lambdas, np.asarray(path)[:, j], label=column)
    axes[0].set_xscale("log"); axes[0].set_xlabel("Lambda"); axes[0].set_ylabel("Coefficient (original units)")
    axes[0].legend(fontsize=7)
    axes[1].errorbar(lambdas, mean_loss, yerr=standard_error)
    axes[1].set_xscale("log"); axes[1].set_xlabel("Lambda"); axes[1].set_ylabel("Validation MSE ± SE")
    for axis in axes:
        axis.axvline(lambdas[min_index], ls="--", color="green")
        axis.axvline(lambdas[one_se_index], ls=":", color="red")
    fig.tight_layout(); fig.savefig(folder / "lasso_paths_and_cv.png"); plt.close(fig)
    prediction = pd.Series(np.nan, index=data.index)
    if PREDICTION_MODEL == "Lasso":
        prediction.loc[can_predict] = lasso.predict(scaler.transform(X.loc[can_predict]))
    else:
        # Refit only nonzero dummy columns, rather than reintroducing excluded levels.
        refit_groups = {column: [column] for column in selected_columns}
        selected = selected_columns
        model = fit_model(y, X, refit_groups, selected, train)
        prediction.loc[can_predict] = model.predict(design(X, refit_groups, selected).loc[can_predict])
        write_summary(model, folder, refit_groups)
    regression_report(data, y, prediction, status, folder)


if __name__ == "__main__":
    main()
