"""Regression tree for numeric Y: fitted rules, tree picture, predictions and evaluation."""
# ---------------- 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.
MIN_SPLIT = 5                  # Shiny tree_minSplit -> min_samples_split.
MIN_BUCKET = 2                 # Shiny tree_minBucket -> min_samples_leaf.
MAX_DEPTH = 3                  # Shiny tree_maxDepth.
CCP_ALPHA = 0.001              # Python pruning alpha; NOT numerically equal to rpart CP.
# R tree_CP=0.001 has a different scale and growth/pruning behavior. See README.
PLOT_MAX_DEPTH = 5             # Limits only the picture, not the fitted tree.

from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, plot_tree, export_text
from model_tools import prepare, output_folder, classification_report, regression_report, plt


def main():
    folder = output_folder(__file__)
    data, y, X, groups, train, can_predict, status = prepare(
        Path(__file__).resolve().parent / DATA_FILE, DELIMITER, Y_COLUMN,
        X_COLUMNS, CATEGORICAL_COLUMNS, sort_by=SORT_BY, holdout_count=HOLDOUT_COUNT)
    model = DecisionTreeRegressor(criterion="squared_error", random_state=9,
        min_samples_split=MIN_SPLIT, min_samples_leaf=MIN_BUCKET,
        max_depth=MAX_DEPTH, ccp_alpha=CCP_ALPHA)
    if X.shape[1] == 0:
        raise ValueError("A tree needs at least one nonconstant X.")
    # Fit only training data. Encoded column names map to original variables below.
    model.fit(X.loc[train], y.loc[train])
    descriptions = {col: name if len(cols)==1 else f"{name} ({col})"
                    for name, cols in groups.items() for col in cols}
    feature_names = [descriptions[col] for col in X.columns]
    text = export_text(model, feature_names=feature_names, max_depth=MAX_DEPTH or 100)
    print(text)
    (folder / "tree_rules.txt").write_text(text + "\nEncoding map:\n" + repr(groups), encoding="utf-8")
    importance = pd.DataFrame({"encoded_column":X.columns,"variable":feature_names,
                               "importance":model.feature_importances_})
    importance.to_csv(folder / "feature_importance.csv", index=False)
    plt.figure(figsize=(17, 8))
    plot_tree(model, feature_names=feature_names, filled=True,
              max_depth=PLOT_MAX_DEPTH, fontsize=8)
    plt.tight_layout(); plt.savefig(folder / "decision_tree.png", dpi=160); plt.close()
    prediction = pd.Series(np.nan, index=data.index)
    prediction.loc[can_predict] = model.predict(X.loc[can_predict])
    regression_report(data, y, prediction, status, folder)


if __name__ == "__main__":
    main()
