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

sns.set_theme(style="whitegrid")

raw = pd.DataFrame({
    "CustomerID":      [101, 102, 103, 104, 105, 106, 107],
    "Age":             [23.0, 45.0, np.nan, 31.0, 22.0, 54.0, 38.0],
    "Annual_Income_k": [50.0, 85.0, 62.0, np.nan, 45.0, 120.0, 350.0],
    "City":            ["New York", "Paris", "New York", "London", np.nan, "London", "Paris"],
})
print("RAW DATASET")
display(raw)

print("Data types / non-null counts:")
raw.info()
print("\nMissing values per column:")
print(raw.isnull().sum())

def impute(frame):
    frame = frame.copy()
    for col in ["Age", "Annual_Income_k"]:          # numerical -> median
        frame[col] = frame[col].fillna(frame[col].median())
    frame["City"] = frame["City"].fillna(frame["City"].mode()[0])   # categorical -> mode
    return frame

raw_imp = impute(raw)
print("After imputation (Age/Income = median, City = mode):")
display(raw_imp)
print("Remaining missing values:", int(raw_imp.isnull().sum().sum()))

def iqr_bounds(s):
    q1, q3 = s.quantile(0.25), s.quantile(0.75)
    iqr = q3 - q1
    return q1, q3, iqr, q1 - 1.5 * iqr, q3 + 1.5 * iqr

def cap_outliers(frame, col):
    frame = frame.copy()
    q1, q3, iqr, lo, hi = iqr_bounds(frame[col])
    n_out = int(((frame[col] < lo) | (frame[col] > hi)).sum())
    frame[col + "_capped"] = frame[col].clip(lo, hi)
    print(f"{col}: Q1={q1:.2f}  Q3={q3:.2f}  IQR={iqr:.2f}  bounds=[{lo:.2f}, {hi:.2f}]  outliers={n_out}")
    return frame

raw_cap = cap_outliers(raw_imp, "Annual_Income_k")
display(raw_cap)

def encode_scale(frame):
    frame = frame.copy()
    le = LabelEncoder()
    frame["City_Encoded"] = le.fit_transform(frame["City"])
    print("City encoding:", {c: int(i) for i, c in enumerate(le.classes_)})
    sc = StandardScaler()
    frame[["Age_Scaled", "Income_Scaled"]] = sc.fit_transform(frame[["Age", "Annual_Income_k_capped"]])
    return frame

raw_final = encode_scale(raw_cap)
display(raw_final)

rng = np.random.default_rng(42)
n = 200
big = pd.DataFrame({
    "CustomerID": np.arange(101, 101 + n),
    "Age": rng.integers(18, 65, n).astype(float),
    "Annual_Income_k": np.round(rng.normal(70, 22, n).clip(20, 140), 1),
    "City": rng.choice(["New York", "Paris", "London", "Tokyo"], n),
})
# a few extreme incomes + random missing values
big.loc[rng.choice(n, 6, replace=False), "Annual_Income_k"] = rng.uniform(300, 450, 6).round(1)
big.loc[rng.choice(n, 20, replace=False), "Age"] = np.nan
big.loc[rng.choice(n, 20, replace=False), "Annual_Income_k"] = np.nan
big.loc[rng.choice(n, 15, replace=False), "City"] = np.nan

print("Missing values before cleaning:\n", big.isnull().sum(), sep="")
df = encode_scale(cap_outliers(impute(big), "Annual_Income_k"))
print("\nMissing values after cleaning:", int(df[["Age", "Annual_Income_k", "City"]].isnull().sum().sum()))
display(df.describe().round(2))

fig, axes = plt.subplots(2, 2, figsize=(13, 8))
sns.histplot(df["Age"], kde=True, ax=axes[0, 0], color="steelblue");                axes[0, 0].set_title("Age distribution")
sns.histplot(df["Annual_Income_k"], kde=True, ax=axes[0, 1], color="indianred");     axes[0, 1].set_title("Income before capping (skewed by outliers)")
sns.histplot(df["Annual_Income_k_capped"], kde=True, ax=axes[1, 0], color="seagreen"); axes[1, 0].set_title("Income after IQR capping")
sns.boxplot(data=df[["Annual_Income_k", "Annual_Income_k_capped"]], ax=axes[1, 1], palette="Set2"); axes[1, 1].set_title("Boxplot: before vs after capping")
plt.tight_layout(); plt.show()

fig, axes = plt.subplots(1, 2, figsize=(14, 5))
sns.countplot(data=df, x="City", hue="City", palette="pastel", legend=False, ax=axes[0]); axes[0].set_title("Customers per city")
corr = df[["Age", "Annual_Income_k_capped", "City_Encoded"]].corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", fmt=".2f", vmin=-1, vmax=1, ax=axes[1]); axes[1].set_title("Correlation heatmap")
plt.tight_layout(); plt.show()
