"""Data explorer — browse the tables in a schema: profile columns, filter,
group and chart, and download what you find."""

import numpy as np
import pandas as pd
import plotly.express as px
import streamlit as st

st.set_page_config(page_title="Data explorer", layout="wide")

# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True explores generated sample tables. Set DEMO = False to explore
# the tables in DATABASE.SCHEMA (read-only; at most ROW_LIMIT rows per table).
DEMO = True
DATABASE = "{{DATABASE}}"
SCHEMA = "{{SCHEMA}}"
TABLES_SQL = "SHOW TABLES IN SCHEMA {{DATABASE}}.{{SCHEMA}}"
ROW_LIMIT = 50_000
# ──────────────────────────────────────────────────────────────────────────────


def demo_tables() -> dict:
    rng = np.random.default_rng(1)
    n = 2000
    customers = pd.DataFrame({
        "CUSTOMER_ID": np.arange(1, 301),
        "SEGMENT": rng.choice(["Enterprise", "Mid-market", "SMB"], 300, p=[0.15, 0.35, 0.5]),
        "COUNTRY": rng.choice(["DE", "US", "UK", "FR", "NL"], 300),
        "SIGNUP_DATE": pd.Timestamp.today().normalize() - pd.to_timedelta(rng.integers(0, 1500, 300), unit="D"),
    })
    orders = pd.DataFrame({
        "ORDER_ID": np.arange(1, n + 1),
        "CUSTOMER_ID": rng.integers(1, 301, n),
        "ORDER_DATE": pd.Timestamp.today().normalize() - pd.to_timedelta(rng.integers(0, 365, n), unit="D"),
        "STATUS": rng.choice(["shipped", "open", "returned"], n, p=[0.8, 0.15, 0.05]),
        "AMOUNT": rng.gamma(2, 180, n).round(2),
    })
    return {"CUSTOMERS": customers, "ORDERS": orders}


@st.cache_data(ttl=600, show_spinner=False)
def list_tables() -> list:
    if DEMO:
        return sorted(demo_tables())
    from snowflake.snowpark.context import get_active_session
    rows = get_active_session().sql(TABLES_SQL).collect()
    return sorted(r["name"] for r in rows)


@st.cache_data(ttl=600, show_spinner=False)
def load_table(name: str) -> pd.DataFrame:
    if DEMO:
        return demo_tables()[name]
    from snowflake.snowpark.context import get_active_session
    # name comes from SHOW TABLES; the list form quotes each part safely
    return get_active_session().table([DATABASE, SCHEMA, name]).limit(ROW_LIMIT).to_pandas()


def profile(df: pd.DataFrame) -> pd.DataFrame:
    rows = []
    for c in df.columns:
        s = df[c]
        numeric = pd.api.types.is_numeric_dtype(s)
        rows.append({
            "COLUMN": c, "TYPE": str(s.dtype), "EMPTY": int(s.isna().sum()), "DISTINCT": int(s.nunique()),
            "MIN": s.min() if numeric or pd.api.types.is_datetime64_any_dtype(s) else None,
            "MAX": s.max() if numeric or pd.api.types.is_datetime64_any_dtype(s) else None,
            "EXAMPLE": str(s.dropna().iloc[0])[:60] if s.notna().any() else "",
        })
    out = pd.DataFrame(rows)
    for c in ("MIN", "MAX"):
        out[c] = out[c].astype(str).replace({"None": "", "NaT": "", "nan": ""})
    return out


st.title("Data explorer")
st.caption("Demo tables — set DEMO = False in the DATA section to explore your schema." if DEMO else f"{DATABASE}.{SCHEMA}")

try:
    tables = list_tables()
except Exception as e:
    st.error(f"Could not list tables: {e}")
    st.stop()
if not tables:
    st.info("No tables in this schema.")
    st.stop()

with st.sidebar:
    table = st.selectbox("Table", tables)

try:
    df = load_table(table)
except Exception as e:
    st.error(f"Could not read {table}: {e}")
    st.stop()
for c in df.columns:  # dates often arrive as strings
    if df[c].dtype == object and ("DATE" in c.upper() or c.upper().endswith("_AT")):
        df[c] = pd.to_datetime(df[c], errors="coerce")

k = st.columns(3)
k[0].metric("Rows loaded", f"{len(df):,}", "limit reached" if len(df) >= ROW_LIMIT else None, delta_color="off")
k[1].metric("Columns", f"{df.shape[1]}")
k[2].metric("Empty cells", f"{int(df.isna().sum().sum()):,}")

tab_data, tab_profile, tab_chart = st.tabs(["Rows", "Columns", "Group & chart"])

with tab_data:
    filtered = df
    col = st.selectbox("Filter column", ["(none)"] + list(df.columns))
    if col != "(none)":
        s = df[col]
        if pd.api.types.is_numeric_dtype(s) and s.notna().any():
            lo, hi = float(s.min()), float(s.max())
            rng_sel = st.slider("Range", lo, hi, (lo, hi)) if lo < hi else (lo, hi)
            filtered = df[s.between(*rng_sel)]
        else:
            values = sorted(s.dropna().astype(str).unique())[:500]
            picked = st.multiselect("Values", values)
            if picked:
                filtered = df[s.astype(str).isin(picked)]
    st.caption(f"{len(filtered):,} rows")
    st.dataframe(filtered.head(2000).reset_index(drop=True), width="stretch")
    st.download_button("Download CSV", filtered.to_csv(index=False), f"{table.lower()}.csv", "text/csv")

with tab_profile:
    st.dataframe(profile(df), width="stretch")

with tab_chart:
    dims = [c for c in df.columns if not pd.api.types.is_numeric_dtype(df[c]) or df[c].nunique() <= 30]
    measures = [c for c in df.columns if pd.api.types.is_numeric_dtype(df[c])]
    if not dims:
        st.info("No column to group by.")
    else:
        c1, c2, c3 = st.columns(3)
        dim = c1.selectbox("Group by", dims)
        how = c2.selectbox("Measure", ["Row count"] + [f"Sum of {m}" for m in measures] + [f"Average of {m}" for m in measures])
        top = c3.slider("Show top", 5, 50, 15)
        key = df[dim].dt.to_period("M").dt.to_timestamp() if pd.api.types.is_datetime64_any_dtype(df[dim]) else df[dim].astype(str)
        if how == "Row count":
            g = df.groupby(key).size().rename("VALUE")
        else:
            agg, m = how.split(" of ", 1)
            g = df.groupby(key)[m].agg("sum" if agg == "Sum" else "mean").rename("VALUE")
        g = g.reset_index().rename(columns={g.index.name or dim: "GROUP"})
        g.columns = ["GROUP", "VALUE"]
        if pd.api.types.is_datetime64_any_dtype(df[dim]):
            fig = px.line(g.sort_values("GROUP"), x="GROUP", y="VALUE", markers=True, labels={"GROUP": dim, "VALUE": how})
        else:
            g = g.sort_values("VALUE", ascending=False).head(top)
            fig = px.bar(g, x="GROUP", y="VALUE", labels={"GROUP": dim, "VALUE": how})
        fig.update_layout(margin=dict(t=30, b=10))
        st.plotly_chart(fig, width="stretch")
