"""Exhaustive search of original-variable subsets, ranked by AIC, BIC or adjusted R²."""
# ---------------- 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.
SELECTION_CRITERION = "AIC"  # "AIC", "BIC", or "adjRsq".
TOP_N_PER_SIZE = 8             # Shiny's showTopN: best N for EACH number of Xs.
MAX_CANDIDATES = 12            # 2**12 = 4096 fits; a runtime guard, not a statistic.

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 itertools import combinations
    if SELECTION_CRITERION not in {"AIC", "BIC", "adjRsq"}:
        raise ValueError("Choose AIC, BIC or adjRsq.")
    if TOP_N_PER_SIZE < 1 or len(groups) > MAX_CANDIDATES:
        raise ValueError("Reduce X_COLUMNS or increase the explicit subset search limit.")
    names = list(groups)
    records, best_model, best_selected, best_score = [], None, [], None
    # Include the intercept-only model; category dummy columns stay together.
    for size in range(len(names) + 1):
        for subset in combinations(names, size):
            try:
                candidate = fit_model(y, X, groups, list(subset), train)
            except ValueError as error:
                print(f"Skipped {subset}: {error}")
                continue
            # R's lm AIC/BIC count the estimated error variance as a parameter.
            # statsmodels omits it: adding 2/log(n) makes these OLS scores R-like.
            values = {"AIC": candidate.aic + 2,
                      "BIC": candidate.bic + np.log(candidate.nobs),
                      "adjRsq": candidate.rsquared_adj}
            records.append({"n_predictors": size, "variables": " + ".join(subset) or "(intercept only)", **values})
            score = -values[SELECTION_CRITERION] if SELECTION_CRITERION == "adjRsq" else values[SELECTION_CRITERION]
            if np.isfinite(score) and (best_score is None or score < best_score):
                best_score, best_model, best_selected = score, candidate, list(subset)
    if best_model is None:
        raise ValueError("No estimable model found.")
    results = pd.DataFrame(records).sort_values(SELECTION_CRITERION,
                                                ascending=SELECTION_CRITERION != "adjRsq")
    results.to_csv(folder / "all_models.csv", index=False)
    top = results.groupby("n_predictors", sort=True).head(TOP_N_PER_SIZE)
    top.to_csv(folder / "top_models_by_size.csv", index=False)
    # Also show each criterion's winner, as the app offers three comparisons.
    winners = []
    for criterion in ["AIC", "BIC", "adjRsq"]:
        row = results.sort_values(criterion, ascending=criterion != "adjRsq").iloc[0].to_dict()
        winners.append({"criterion": criterion, **row})
    pd.DataFrame(winners).to_csv(folder / "criterion_winners.csv", index=False)
    print(top.to_string(index=False))
    selected, model = best_selected, best_model
    print(f"Best by {SELECTION_CRITERION}:", selected or "Intercept only")
    # Predict rows with complete X, even if their Y is missing (future periods).
    prediction = pd.Series(np.nan, index=data.index)
    prediction.loc[can_predict] = model.predict(design(X, groups, selected).loc[can_predict])
    write_summary(model, folder, groups)
    regression_report(data, y, prediction, status, folder)


if __name__ == "__main__":
    main()
