import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

X, y = make_blobs(
    n_samples=300, centers=4, cluster_std=1.0, random_state=42
)

print(f"Dataset generated: {X.shape[0]} points, {X.shape[1]} features")

wcss = []
k_range = range(1, 11)

for k in k_range:
    model = KMeans(n_clusters=k, random_state=42, n_init=10)
    model.fit(X)
    wcss.append(model.inertia_)

plt.figure(figsize=(7, 4))
plt.plot(k_range, wcss, marker='o', color='b', linewidth=2)
plt.xlabel("Number of Clusters (K)")
plt.ylabel("WCSS (Inertia)")
plt.title("Elbow Method for Optimal K")
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()

records = []

for k in range(2, 11):
    model = KMeans(n_clusters=k, random_state=42, n_init=10)
    cluster_labels = model.fit_predict(X)
    score = silhouette_score(X, cluster_labels)
    records.append({'K': k, 'WCSS': round(model.inertia_, 2), 'Silhouette Score': round(score, 4)})

summary_df = pd.DataFrame(records)
print("=== K Evaluation Metrics ===")
print(summary_df.to_string(index=False))
print("\nNotice: Highest Silhouette Score occurs at K = 4!")

optimal_k = 4
final_model = KMeans(n_clusters=optimal_k, random_state=42, n_init=10)
final_labels = final_model.fit_predict(X)

plt.figure(figsize=(8, 5))
plt.scatter(X[:, 0], X[:, 1], c=final_labels, cmap='rainbow', s=35, alpha=0.7)

centroids = final_model.cluster_centers_
plt.scatter(
    centroids[:, 0], centroids[:, 1],
    color='black', marker='X', s=200, label='Centroids'
)

plt.title(f"K-Means Clustering with Optimal K = {optimal_k}")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.legend()
plt.grid(True, linestyle='--', alpha=0.5)
plt.show()
