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
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (accuracy_score, precision_score, recall_score, f1_score, roc_auc_score,
                             confusion_matrix, ConfusionMatrixDisplay, RocCurveDisplay)

sns.set_theme(style="whitegrid")
data = pd.read_csv("heart_disease_data.csv")
print("Shape:", data.shape)
display(data.head())

print("Missing values:\n", data.isnull().sum(), sep="")
dups = int(data.duplicated().sum())
print(f"\nDuplicate rows: {dups}")
if dups:
    data = data.drop_duplicates().reset_index(drop=True)   # a duplicate could leak between train and test
    print("Duplicates dropped, new shape:", data.shape)
print("\nClass balance (0 = No Disease, 1 = Disease):")
print(data["Heart_Disease"].value_counts())
sns.countplot(data=data, x="Heart_Disease", hue="Heart_Disease", palette="Set2", legend=False); plt.title("Class balance"); plt.show()

features = ["Age", "Resting_Blood_Pressure", "Cholesterol", "Maximum_Heart_Rate", "Exercise_Induced_Angina"]
X = data[features]
y = data["Heart_Disease"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42, stratify=y)
print(f"Training samples: {len(X_train)}   Testing samples: {len(X_test)}")

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)   # fit on training data only
X_test_scaled = scaler.transform(X_test)

model = LogisticRegression(random_state=42)
model.fit(X_train_scaled, y_train)
print("Model trained.")

y_pred = model.predict(X_test_scaled)
y_prob = model.predict_proba(X_test_scaled)[:, 1]

print("Model Performance")
print("-----------------")
print("Accuracy :", round(accuracy_score(y_test, y_pred), 4))
print("Precision:", round(precision_score(y_test, y_pred, zero_division=0), 4))
print("Recall   :", round(recall_score(y_test, y_pred, zero_division=0), 4))
print("F1-Score :", round(f1_score(y_test, y_pred, zero_division=0), 4))
print("ROC-AUC  :", round(roc_auc_score(y_test, y_prob), 4))
cm = confusion_matrix(y_test, y_pred)
print("\nConfusion Matrix:\n", cm)

fig, axes = plt.subplots(1, 3, figsize=(18, 5))
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", ax=axes[0], xticklabels=["No disease", "Disease"], yticklabels=["No disease", "Disease"])
axes[0].set_title("Confusion Matrix - Heart Disease Prediction"); axes[0].set_xlabel("Predicted"); axes[0].set_ylabel("Actual")
RocCurveDisplay.from_predictions(y_test, y_prob, ax=axes[1]); axes[1].plot([0, 1], [0, 1], "k--"); axes[1].set_title("ROC Curve")
for cls, col in [(0, "tomato"), (1, "seagreen")]:
    axes[2].hist(y_prob[y_test.values == cls], bins=8, alpha=.6, color=col, label=f"Actual class {cls}")
axes[2].axvline(0.5, color="k", ls="--"); axes[2].set_title("Predicted probability by class"); axes[2].set_xlabel("P(Heart disease)"); axes[2].legend()
plt.tight_layout(); plt.show()

coeffs = pd.DataFrame({"Feature": features, "Coefficient": model.coef_[0], "Odds ratio": np.exp(model.coef_[0])})
display(coeffs.sort_values("Coefficient", ascending=False).round(4))
print("Intercept:", round(float(model.intercept_[0]), 4))

rows = []
for t in [0.3, 0.4, 0.5, 0.6, 0.7]:
    pred_t = (y_prob >= t).astype(int)
    rows.append({"Threshold": t,
                 "Accuracy": accuracy_score(y_test, pred_t),
                 "Precision": precision_score(y_test, pred_t, zero_division=0),
                 "Recall": recall_score(y_test, pred_t, zero_division=0),
                 "F1": f1_score(y_test, pred_t, zero_division=0)})
display(pd.DataFrame(rows).round(4))

new_patient = pd.DataFrame([{"Age": 55, "Resting_Blood_Pressure": 140, "Cholesterol": 240,
                             "Maximum_Heart_Rate": 150, "Exercise_Induced_Angina": 1}])
new_scaled = scaler.transform(new_patient)
prediction = model.predict(new_scaled)[0]
probability = model.predict_proba(new_scaled)[0, 1]
print("New Patient Prediction")
print("----------------------")
print("Probability of Heart Disease:", round(float(probability), 4))
print("Prediction:", "Heart Disease Present" if prediction == 1 else "No Heart Disease")
