import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import warnings

warnings.filterwarnings("ignore", category=UserWarning)


def smart_viz(df, max_cats=10, max_plots=6):
    """
    Clean, readable, smart EDA visualization for ANY dataset.
    - Limits plots for large datasets
    - Handles high-cardinality columns
    - Prevents mathtext crashes ($ symbols)
    """

    print("\n[Essentia] 📊 Starting Smart Visualization...\n")

    sns.set(style="whitegrid")
    plt.rcParams["text.usetex"] = False   # Fix Joey Bada$$ bug
    plt.rcParams["figure.dpi"] = 100

    # 1️⃣ NUMERIC DATA
    num_df = df.select_dtypes(include=["int64", "float64"])

    # Correlation heatmap
    if len(num_df.columns) > 1:
        print("[Essentia] 🔹 Correlation Heatmap for Numeric Features")
        plt.figure(figsize=(8, 5))
        sns.heatmap(num_df.corr(), cmap="coolwarm", annot=True, fmt=".2f")
        plt.title("Correlation Heatmap")
        plt.tight_layout()
        plt.show()
    elif len(num_df.columns) == 1:
        print("[Essentia] ⚠ Only one numeric column — skipping heatmap.")
    else:
        print("[Essentia] ⚠ No numeric columns found.")

    # Numeric distributions
    for col in num_df.columns[:max_plots]:
        plt.figure(figsize=(6, 4))
        sns.histplot(df[col], kde=True)
        plt.title(f"Distribution: {col}")
        plt.xlabel(col)
        plt.tight_layout()
        plt.show()

    # Numeric boxplots
    for col in num_df.columns[:max_plots]:
        plt.figure(figsize=(6, 4))
        sns.boxplot(x=df[col], color="lightgreen")
        plt.title(f"Boxplot: {col}")
        plt.tight_layout()
        plt.show()

    # 2️⃣ CATEGORICAL DATA
    cat_df = df.select_dtypes(include=["object"])

    for col in cat_df.columns[:max_plots]:
        # Only show top 10 categories
        top_vals = df[col].value_counts().nlargest(max_cats)

        plt.figure(figsize=(8, 4))
        sns.barplot(
            x=top_vals.values,
            y=top_vals.index,
            palette="viridis",
            hue=None,
            legend=False
        )
        plt.title(f"Top {max_cats} Categories in {col}")
        plt.xlabel("Count")
        plt.ylabel(col)
        plt.tight_layout()
        plt.show()

    # 3️⃣ PAIRPLOT (safe mode)
    if 2 <= len(num_df.columns) <= 5:
        print("[Essentia] 🔹 Pairplot (numeric relationships)")
        sns.pairplot(num_df)
        plt.show()
    else:
        print("[Essentia] ⚠ Skipping pairplot — too many or too few numeric columns.")

    # 4️⃣ Insights Summary
    print("\n[Essentia] 💡 Auto Insights Summary")
    print("--------------------------------------------")
    print(f"Numeric Columns: {len(num_df.columns)}")
    print(f"Categorical Columns: {len(cat_df.columns)}")
    if not cat_df.empty:
        smallest_cat = cat_df.columns[df[cat_df.columns].nunique().argmin()]
        print(f"Least Unique Categorical Column: {smallest_cat}")
    if not num_df.empty:
        print(f"Numeric Column with Highest Variance: {df[num_df.columns].var().idxmax()}")
    print("--------------------------------------------")

    print("\n[Essentia] ✅ Smart Visualization Completed!\n")
