"""Bidirectional linear stepwise selection using partial F-test significance."""
# ---------------- 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.
SLE = 0.15  # Significance level to ENTER (same default as Shiny).
SLS = 0.05  # Significance level to STAY (same default as Shiny; see README on cycles).
MAX_STEPS = 100

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)
    selected, model, history = stepwise(y, X, groups, train, SLE, SLS,
                                        max_steps=MAX_STEPS)
    print("Selected variables:", selected or "Intercept only")
    print(history.to_string(index=False))
    history.to_csv(folder / "selection_history.csv", index=False)
    # 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()
