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

def load_data(file_path):
    df = pd.read_csv(file_path)
    return df

def preprocess_data(df):
    features = ['Frequency', 'Recency', 'Monetary', 'rankR', 'rankF', 'rankM']
    scaler = StandardScaler()
    df_scaled = scaler.fit_transform(df[features])
    df_scaled = pd.DataFrame(df_scaled, columns=features)
    return df_scaled

def determine_optimal_clusters(df_scaled):
    wcss = []
    for i in range(1, 11):
        kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=42)
        kmeans.fit(df_scaled)
        wcss.append(kmeans.inertia_)
    plt.figure(figsize=(10, 6))
    plt.plot(range(1, 11), wcss, marker='o')
    plt.title('Elbow Method')
    plt.xlabel('Number of clusters')
    plt.ylabel('WCSS')
    plt.show()

def build_kmeans_model(df_scaled, optimal_clusters):
    kmeans = KMeans(n_clusters=optimal_clusters, init='k-means++', max_iter=300, n_init=10, random_state=42)
    cluster_labels = kmeans.fit_predict(df_scaled)
    return cluster_labels

def analyze_clusters(df, cluster_labels):
    df['Cluster'] = cluster_labels
    features = ['Frequency', 'Recency', 'Monetary', 'rankR', 'rankF', 'rankM']
    cluster_analysis = df.groupby('Cluster')[features].mean()
    print(cluster_analysis)
    plt.figure(figsize=(12, 8))
    sns.scatterplot(x='Frequency', y='Monetary', hue='Cluster', data=df, palette='viridis')
    plt.title('Customer Segments')
    plt.xlabel('Frequency')
    plt.ylabel('Monetary')
    plt.legend()
    plt.show()
    sns.pairplot(df, hue='Cluster', palette='viridis', diag_kind='kde')
    plt.show()

def main():
    file_path = 'ecom_data_rfm.csv'  # Update with your file path
    df = load_data(file_path)
    print(df.head())
    print(df.isnull().sum())
    df_scaled = preprocess_data(df)
    determine_optimal_clusters(df_scaled)
    optimal_clusters = 4  # Update based on the Elbow Method
    cluster_labels = build_kmeans_model(df_scaled, optimal_clusters)
    analyze_clusters(df, cluster_labels)

if __name__ == "__main__":
    main()
