import pandas as pd
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score

# 1. LOAD DATASET

df = pd.read_csv("Churn_Modelling(2).csv")

print(df.head())
print("Missing Values:\n", df.isnull().sum())

# 2. EDA AND CLASS DISTRIBUTION

print("Class Distribution:\n", df["Exited"].value_counts())

df["Exited"].value_counts().plot(kind="bar")
plt.title("Customer Churn Distribution")
plt.xlabel("Exited (0 = Stayed, 1 = Left)")
plt.ylabel("Number of Customers")
plt.show()

df.boxplot(column="Age", by="Exited")
plt.title("Age vs Customer Churn")
plt.suptitle("")

plt.show()

# 3. PREPARE FEATURES AND TARGET

df = df.dropna().drop_duplicates()

X = df.drop(columns=["Exited", "RowNumber", "CustomerId", "Surname"])
y = df["Exited"]

X = pd.get_dummies(X, dtype=int)

print("Features:", X.columns)
print("Target: Exited")

# 4. TRAIN-TEST SPLIT

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# TRAIN DECISION TREE

model = DecisionTreeClassifier(
    criterion="gini", max_depth=4, random_state=42
)

model.fit(X_train, y_train)

# 5. PREDICT CHURN

y_pred = model.predict(X_test)

comparison = pd.DataFrame({
    "Actual": y_test.values,
    "Predicted": y_pred
})

print("\nActual vs Predicted:\n", comparison.head(10))

# 6. EVALUATE MODEL

print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall:", recall_score(y_test, y_pred))
print("F1 Score:", f1_score(y_test, y_pred))
