"""Lightweight stats check and visualization helpers."""

import pandas as pd

def quick_check(gdf):
    '''Print basic sanity checks for a GeoDataFrame.'''
    print(f"rows, cols: {gdf.shape}")

    if "GEOID" in gdf.columns:
        print(f"unique GEOID: {gdf['GEOID'].nunique()}")

    missing = (gdf.isna().mean() * 100).round(2).sort_values(ascending=False)
    print("n/a values (%):")
    print(missing.head(10))

def quick_viz(gdf, col, save_path=None):
    ''' Map + histogram.'''
    if "geometry" not in gdf.columns:
        raise ValueError("quick_viz requires a GeoDataFrame with geometry.")
    if col not in gdf.columns:
        raise ValueError(f"Column '{col}' not found.")

    plot_gdf = gdf
    if hasattr(plot_gdf, "crs") and plot_gdf.crs is not None and plot_gdf.crs.is_geographic:
        bounds = plot_gdf.total_bounds
        width = bounds[2] - bounds[0]
        height = bounds[3] - bounds[1]
        in_conus_bbox = (
            bounds[0] >= -130 and bounds[2] <= -60 and
            bounds[1] >= 20 and bounds[3] <= 55
        )
        # Use a CONUS projection only when the extent is nation-scale and CONUS-bounded.
        if width >= 30 and height >= 12 and in_conus_bbox:
            plot_gdf = plot_gdf.to_crs(epsg=5070)

    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 2, figsize=(12, 5))

    map_ax = plot_gdf.plot(
        column=col,
        cmap="Blues",
        legend=True,
        ax=axes[0],
        legend_kwds={"shrink": 0.8},
    )
    # geopandas uses matplotlib colorbar; adjust after creation
    cbar_ax = map_ax.get_figure().axes[-1]
    cbar_ax.set_ylabel(col, fontsize=16, rotation=270, labelpad=15)
    cbar_ax.tick_params(labelsize=14)
    axes[0].set_title(col, fontsize=17, pad=10)
    axes[0].set_axis_off()

    series = pd.to_numeric(plot_gdf[col], errors="coerce")
    missing_pct = series.isna().mean() * 100
    if missing_pct > 50:
        raise ValueError(
            f"Column '{col}' has too many missing values to plot ({missing_pct:.1f}%)."
        )
    if series.notna().sum() == 0:
        raise ValueError(f"Column '{col}' has no numeric values to plot.")

    series.plot.hist(
        bins=30,
        color="#4c78a8",
        edgecolor="white",
        ax=axes[1],
    )
    avg_val = series.mean()
    if pd.notna(avg_val):
        axes[1].axvline(avg_val, color="black", linewidth=1.5, linestyle="--")
        axes[1].annotate(
            "avg.",
            xy=(avg_val, 1),
            xycoords=("data", "axes fraction"),
            xytext=(4, -6),
            textcoords="offset points",
            ha="left",
            va="top",
            fontsize=12,
            fontweight="normal",
            color="black",
        )
    axes[1].set_title(f"{col} Distribution", fontsize=17, pad=10)
    axes[1].set_xlabel(col, fontsize=16)
    axes[1].set_ylabel("Frequency", fontsize=16)
    axes[1].tick_params(axis='both', labelsize=14)
    plt.tight_layout()
    if save_path:
        fig.savefig(save_path, dpi=200, bbox_inches="tight")
    plt.show()
