"""Binary classification tree: fitted rules, tree picture, predictions and evaluation."""
# ---------------- SETTINGS: edit these before running ----------------
DATA_FILE = "data/churn.csv"
DELIMITER = None
Y_COLUMN = "Churn?"
X_COLUMNS = ["Day Mins", "Eve Mins", "Intl Mins", "CustServ Calls", "Int'l Plan", "VMail Plan"]
CATEGORICAL_COLUMNS = []        # Text categories are encoded automatically.
POSITIVE_CLASS = 1              # Recognizes True./False. in the telecom CSV.
PROBABILITY_CUTOFF = 0.5
HOLDOUT_PERCENT = 0             # Shiny classification holdouts are a PERCENT, not a count.
RANDOM_SEED = 9
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__)
    if not 0 <= HOLDOUT_PERCENT < 100:
        raise ValueError("HOLDOUT_PERCENT must be from 0 to less than 100.")
    data, y, X, groups, train, can_predict, status = prepare(
        Path(__file__).resolve().parent / DATA_FILE, DELIMITER, Y_COLUMN,
        X_COLUMNS, CATEGORICAL_COLUMNS, test_fraction=HOLDOUT_PERCENT/100,
        seed=RANDOM_SEED, classification=True, positive_class=POSITIVE_CLASS)
    model = DecisionTreeClassifier(criterion="gini", random_state=RANDOM_SEED,
        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()
    # predict_proba columns follow model.classes_; find positive class explicitly.
    positive_index = list(model.classes_).index(1)
    probability = pd.Series(np.nan, index=data.index)
    probability.loc[can_predict] = model.predict_proba(X.loc[can_predict])[:, positive_index]
    classification_report(data, y, probability, status, PROBABILITY_CUTOFF, folder)


if __name__ == "__main__":
    main()
