import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.tree import DecisionTreeClassifier, export_text, plot_tree
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, roc_auc_score

sns.set_theme(style="whitegrid")
np.random.seed(42)
n_samples = 1000
data = {
    "Debt_to_Income_Ratio": np.random.uniform(0.1, 0.8, n_samples),
    "Credit_Score": np.random.randint(300, 850, n_samples),
    "Annual_Income": np.random.uniform(20000, 150000, n_samples),
    "Missed_Payments_Count": np.random.randint(0, 10, n_samples),
}
df = pd.DataFrame(data)
risk_index = (df["Debt_to_Income_Ratio"] * 2.5) + (df["Missed_Payments_Count"] * 0.4) - (df["Credit_Score"] / 300.0)
df["Credit_Risk_Rating"] = pd.qcut(risk_index, q=3, labels=[0, 1, 2]).astype(int)

display(df.head())
print(df["Credit_Risk_Rating"].value_counts().sort_index())

feature_cols = ["Debt_to_Income_Ratio", "Credit_Score", "Annual_Income", "Missed_Payments_Count"]
X = df[feature_cols]
y = df["Credit_Risk_Rating"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42, stratify=y)
print("Train:", X_train.shape, " Test:", X_test.shape)

dt_model = DecisionTreeClassifier(criterion="gini", max_depth=4, min_samples_split=10, min_samples_leaf=5, random_state=42)
dt_model.fit(X_train, y_train)
print("Depth:", dt_model.get_depth(), "| leaves:", dt_model.get_n_leaves())

names = ["Low Risk", "Moderate Risk", "High Risk"]
y_pred = dt_model.predict(X_test)
y_probs = dt_model.predict_proba(X_test)
cm = confusion_matrix(y_test, y_pred)

print("Train accuracy:", round(dt_model.score(X_train, y_train), 4), "| Test accuracy:", round(accuracy_score(y_test, y_pred), 4))
print("\n--- Confusion Matrix ---"); print(cm)
print("\n--- Classification Report ---")
print(classification_report(y_test, y_pred, target_names=names))
print(f"ROC-AUC (OvR): {roc_auc_score(y_test, y_probs, multi_class='ovr'):.4f}")

feature_imp = pd.Series(dt_model.feature_importances_, index=X.columns).sort_values(ascending=False)
print("--- Feature Importances ---"); print(feature_imp.round(4))

fig, axes = plt.subplots(1, 2, figsize=(14, 5))
sns.barplot(x=feature_imp.values, y=feature_imp.index, hue=feature_imp.index, palette="viridis", legend=False, ax=axes[0])
axes[0].set_title("Feature Importance (Gini)")
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=names, yticklabels=names, ax=axes[1])
axes[1].set_title("Confusion Matrix"); axes[1].set_xlabel("Predicted"); axes[1].set_ylabel("Actual")
plt.tight_layout(); plt.show()

print("--- Decision Tree Rules ---")
print(export_text(dt_model, feature_names=list(X.columns))[:1500])

plt.figure(figsize=(24, 10))
plot_tree(dt_model, feature_names=X.columns, class_names=names, filled=True, rounded=True, fontsize=8)
plt.title("Decision Tree (max_depth = 4)"); plt.show()

rows = []
for crit in ["gini", "entropy"]:
    m = DecisionTreeClassifier(criterion=crit, max_depth=4, min_samples_split=10, min_samples_leaf=5, random_state=42).fit(X_train, y_train)
    rows.append({"Criterion": crit, "Train acc": m.score(X_train, y_train), "Test acc": m.score(X_test, y_test),
                 "CV acc (5-fold)": cross_val_score(m, X_train, y_train, cv=5).mean()})
display(pd.DataFrame(rows).round(4))

depths = range(1, 16)
tr, te = [], []
for d in depths:
    m = DecisionTreeClassifier(max_depth=d, random_state=42).fit(X_train, y_train)
    tr.append(m.score(X_train, y_train)); te.append(m.score(X_test, y_test))
plt.figure(figsize=(8, 5)); plt.plot(depths, tr, "o-", label="Train"); plt.plot(depths, te, "s-", label="Test")
plt.xlabel("max_depth"); plt.ylabel("Accuracy"); plt.title("Overfitting with increasing depth"); plt.legend(); plt.show()

path = DecisionTreeClassifier(random_state=42).cost_complexity_pruning_path(X_train, y_train)
alphas = np.unique(path.ccp_alphas[:-1])
alphas = alphas[:: max(1, len(alphas) // 40)]            # keep the loop fast

cv_means = [cross_val_score(DecisionTreeClassifier(ccp_alpha=a, random_state=42), X_train, y_train, cv=5).mean() for a in alphas]
best_alpha = alphas[int(np.argmax(cv_means))]
pruned = DecisionTreeClassifier(ccp_alpha=best_alpha, random_state=42).fit(X_train, y_train)

plt.figure(figsize=(8, 5)); plt.plot(alphas, cv_means, marker="o", ms=3)
plt.axvline(best_alpha, color="r", ls="--", label=f"best alpha = {best_alpha:.5f}")
plt.xlabel("ccp_alpha"); plt.ylabel("CV accuracy"); plt.title("Cost-complexity pruning"); plt.legend(); plt.show()

print(f"Best ccp_alpha: {best_alpha:.5f}")
print(f"Pre-pruned tree : depth={dt_model.get_depth()}, leaves={dt_model.get_n_leaves()}, test acc={dt_model.score(X_test, y_test):.4f}")
print(f"CCP-pruned tree : depth={pruned.get_depth()}, leaves={pruned.get_n_leaves()}, test acc={pruned.score(X_test, y_test):.4f}")
