import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score

import os

# Load the Mall Customers dataset if it is next to this notebook; otherwise generate a
# Mall-Customers-style synthetic dataset (200 customers in 5 spending segments) and save it.
file_path = 'Mall_Customers.csv'
if os.path.exists(file_path):
    df = pd.read_csv(file_path)
else:
    rng = np.random.default_rng(42)
    segments = [  # (customers, mean income k$, mean spending score)
        (23, 25, 78), (21, 88, 17), (22, 26, 20), (20, 88, 82), (114, 55, 50)]
    pts = np.vstack([
        np.c_[np.clip(rng.normal(inc, 7, n_c).round(), 15, 137),
              np.clip(rng.normal(spend, 7, n_c).round(), 1, 99)]
        for n_c, inc, spend in segments])
    n = len(pts)
    df = pd.DataFrame({
        'CustomerID': np.arange(1, n + 1),
        'Gender': rng.choice(['Male', 'Female'], n),
        'Age': rng.integers(18, 70, n),
        'Annual Income (k$)': pts[:, 0].astype(int),
        'Spending Score (1-100)': pts[:, 1].astype(int),
    })
    df.to_csv(file_path, index=False)
    print('Mall_Customers.csv not found -> generated a synthetic Mall-style dataset and saved it as', file_path)

# Basic Inspection
print("--- First 5 Rows of the Dataset ---")
display(df.head())

print("\n--- Dataset Shape ---")
print(df.shape)

print("\n--- Dataset Info (Columns and Data Types) ---")
df.info()

print("\n--- Missing Values Summary ---")
print(df.isnull().sum())

print("\n--- Duplicate Records Summary ---")
print(f"Number of duplicate rows: {df.duplicated().sum()}")

print("\n--- Summary Statistics ---")
display(df.describe())

sns.set_theme(style='whitegrid')

# 1. Distribution of numerical variables
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
sns.histplot(df['Age'], bins=15, kde=True, ax=axes[0], color='skyblue')
axes[0].set_title('Distribution of Age')

sns.histplot(df['Annual Income (k$)'], bins=15, kde=True, ax=axes[1], color='salmon')
axes[1].set_title('Distribution of Annual Income (k$)')

sns.histplot(df['Spending Score (1-100)'], bins=15, kde=True, ax=axes[2], color='lightgreen')
axes[2].set_title('Distribution of Spending Score (1-100)')
plt.tight_layout()
plt.show()

# 2. Gender distribution if exists
if 'Gender' in df.columns:
    plt.figure(figsize=(6, 4))
    sns.countplot(data=df, x='Gender', palette='pastel', hue='Gender', legend=False)
    plt.title('Distribution of Gender')
    plt.show()

# 3. Scatter Plot: Annual Income vs Spending Score
plt.figure(figsize=(8, 6))
sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)', s=80, color='purple', alpha=0.7)
plt.title('Annual Income vs Spending Score')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()

# Select primary clustering features
features = ['Annual Income (k$)', 'Spending Score (1-100)']
X = df[features].values

# Scale the features using StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

print("First 5 rows of scaled features:")
print(X_scaled[:5])

wcss = []
silhouette_scores = []
k_range = range(2, 11)

for k in k_range:
    kmeans = KMeans(n_clusters=k, init='k-means++', random_state=42, n_init=10)
    kmeans.fit(X_scaled)
    wcss.append(kmeans.inertia_)
    silhouette_scores.append(silhouette_score(X_scaled, kmeans.labels_))

# Create summary table
metrics_df = pd.DataFrame({
    'Number of Clusters (K)': list(k_range),
    'WCSS (Inertia)': wcss,
    'Silhouette Score': silhouette_scores
})
print("--- K-Means Evaluation Metrics Summary ---")
display(metrics_df.round(4))

# Plot the elbow and silhouette scores side-by-side
fig, axes = plt.subplots(1, 2, figsize=(16, 5))

# Elbow plot
axes[0].plot(k_range, wcss, marker='o', color='darkred', linestyle='--')
axes[0].set_title('Elbow Method (WCSS vs K)')
axes[0].set_xlabel('Number of Clusters (K)')
axes[0].set_ylabel('WCSS')
axes[0].set_xticks(k_range)

# Silhouette plot
axes[1].plot(k_range, silhouette_scores, marker='s', color='darkblue', linestyle='--')
axes[1].set_title('Silhouette Analysis (Score vs K)')
axes[1].set_xlabel('Number of Clusters (K)')
axes[1].set_ylabel('Silhouette Score')
axes[1].set_xticks(k_range)

plt.tight_layout()
plt.show()

# Final model training
optimal_k = 5
final_kmeans = KMeans(n_clusters=optimal_k, init='k-means++', random_state=42, n_init=10)
cluster_labels = final_kmeans.fit_predict(X_scaled)

# Add cluster labels to a copy of original DataFrame
df_clustered = df.copy()
df_clustered['Cluster'] = cluster_labels

print("--- Sample of Clustered Customer Data ---")
display(df_clustered.head())

# Inverse transform scaled centroids back to original scale
centroids_scaled = final_kmeans.cluster_centers_
centroids_original = scaler.inverse_transform(centroids_scaled)

plt.figure(figsize=(10, 8))
# Plot clusters
sns.scatterplot(
    data=df_clustered,
    x='Annual Income (k$)',
    y='Spending Score (1-100)',
    hue='Cluster',
    palette='Set1',
    s=90,
    alpha=0.8,
    style='Cluster'
)

# Plot original space centroids
plt.scatter(
    centroids_original[:, 0],
    centroids_original[:, 1],
    s=350,
    c='black',
    marker='*',
    label='Centroids',
    edgecolor='yellow',
    linewidths=1.5
)

plt.title('Customer Segments Visualized (K = 5)', fontsize=14)
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.grid(True, linestyle=':', alpha=0.6)
plt.show()

# Calculate profiling characteristics for each cluster
profile_summary = df_clustered.groupby('Cluster').agg({
    'CustomerID': 'count',
    'Age': 'mean',
    'Annual Income (k$)': 'mean',
    'Spending Score (1-100)': 'mean'
}).rename(columns={'CustomerID': 'Customer Count'})

print("--- Cluster Means Summary Table ---")
display(profile_summary.round(2))

# Show direct numerical values dynamically
print(f"Final K value: {optimal_k}")
print(f"Final WCSS (Inertia): {final_kmeans.inertia_:.4f}")
print(f"Final Silhouette Score: {silhouette_score(X_scaled, final_kmeans.labels_):.4f}")
