"""Customer feedback with Cortex AI — sentiment and topics of reviews, tickets
or survey answers, scored in Snowflake, with an AI summary of the complaints."""

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

st.set_page_config(page_title="Customer feedback", layout="wide")

# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True runs on generated comments with ready-made scores. Set
# DEMO = False to score your own table with Cortex AI in Snowflake (the role
# needs the database role SNOWFLAKE.CORTEX_USER; Cortex bills per token, so
# the query keeps the last 90 days and at most 5,000 comments).
DEMO = True
FEEDBACK_SQL = """
SELECT FEEDBACK_DATE, SOURCE, FEEDBACK_TEXT,
       SNOWFLAKE.CORTEX.SENTIMENT(FEEDBACK_TEXT) AS SENTIMENT,
       AI_CLASSIFY(FEEDBACK_TEXT, ['Delivery', 'Price', 'Product quality', 'Support', 'Ease of use']):labels[0]::STRING AS TOPIC
FROM {{DATABASE}}.{{SCHEMA}}.FEEDBACK
WHERE FEEDBACK_DATE >= DATEADD(day, -90, CURRENT_DATE())
ORDER BY FEEDBACK_DATE DESC
LIMIT 5000
"""
SUMMARY_SQL = """
SELECT AI_SUMMARIZE_AGG(FEEDBACK_TEXT)
FROM {{DATABASE}}.{{SCHEMA}}.FEEDBACK
WHERE FEEDBACK_DATE >= DATEADD(day, -30, CURRENT_DATE())
  AND SNOWFLAKE.CORTEX.SENTIMENT(FEEDBACK_TEXT) < -0.3
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = {"Negative": "#d62728", "Neutral": "#9aa5b1", "Positive": "#2ca02c"}
PHRASES = {
    "Delivery": (["Parcel arrived a week late and nobody told me.", "Courier left it in the rain, box soaked."],
                 ["Arrived a day early, well packed.", "Tracking was spot on, delivery on time."]),
    "Price": (["Too expensive for what you get.", "Shipping costs doubled the price."],
              ["Fair price for the quality.", "Great value, cheaper than the shop down the road."]),
    "Product quality": (["Broke after two weeks.", "The zip came off on the first day."],
                        ["Feels solid and well made.", "Still works perfectly after months of daily use."]),
    "Support": (["Waited 40 minutes on the phone, then got cut off.", "Three emails and still no answer."],
                ["Support sorted it in five minutes, thank you.", "Friendly agent, refund the same day."]),
    "Ease of use": (["The app keeps logging me out.", "Setup instructions make no sense."],
                    ["Set up in two minutes, very easy.", "The new app is much simpler to use."]),
}
DEMO_SUMMARY = ("Most complaints in the last 30 days are about late or damaged deliveries and slow support replies: "
                "customers mention parcels arriving days late without notice and waiting a long time on the phone. "
                "A smaller group finds shipping costs too high, and a few report products breaking within weeks.")


def demo_feedback() -> pd.DataFrame:
    rng = np.random.default_rng(5)
    n = 1400
    topics = rng.choice(list(PHRASES), n, p=[0.3, 0.15, 0.2, 0.25, 0.1])
    days = pd.Timestamp.today().normalize() - pd.to_timedelta(rng.integers(0, 90, n), unit="D")
    trend = (days - days.min()).days.to_numpy() / 90          # complaints about delivery grow over time
    rows = []
    for t, d, tr in zip(topics, days, trend):
        p_neg = 0.35 + (0.25 * tr if t == "Delivery" else 0)
        negative = rng.random() < p_neg
        text = rng.choice(PHRASES[t][0 if negative else 1])
        score = rng.uniform(-0.95, -0.35) if negative else rng.uniform(0.2, 0.95)
        if rng.random() < 0.15:
            score = rng.uniform(-0.25, 0.25)
        rows.append((d, rng.choice(["App store", "Website", "Support tickets", "Survey"]), text, round(score, 3), t))
    return pd.DataFrame(rows, columns=["FEEDBACK_DATE", "SOURCE", "FEEDBACK_TEXT", "SENTIMENT", "TOPIC"])


@st.cache_data(ttl=3600, show_spinner="Scoring feedback with Cortex AI…")
def load_feedback() -> pd.DataFrame:
    if DEMO:
        df = demo_feedback()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(FEEDBACK_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    df["FEEDBACK_DATE"] = pd.to_datetime(df["FEEDBACK_DATE"], errors="coerce")
    df["SENTIMENT"] = pd.to_numeric(df["SENTIMENT"], errors="coerce").fillna(0.0)
    for c in ("SOURCE", "TOPIC", "FEEDBACK_TEXT"):
        df[c] = df[c].fillna("Unknown").astype(str).str.strip('"')
    df["MOOD"] = np.select([df["SENTIMENT"] < -0.3, df["SENTIMENT"] > 0.3], ["Negative", "Positive"], default="Neutral")
    return df.dropna(subset=["FEEDBACK_DATE"])


@st.cache_data(ttl=3600, show_spinner="Summarising with Cortex AI…")
def complaint_summary() -> str:
    if DEMO:
        return DEMO_SUMMARY
    from snowflake.snowpark.context import get_active_session
    rows = get_active_session().sql(SUMMARY_SQL).collect()
    return str(rows[0][0]) if rows and rows[0][0] else "No negative feedback in the last 30 days."


st.title("Customer feedback")
if DEMO:
    st.caption("Showing generated comments with ready-made scores — set DEMO = False in the DATA section to score your own with Cortex AI.")

try:
    data = load_feedback()
except Exception as e:
    st.error(f"Could not load feedback: {e}. Scoring needs the database role SNOWFLAKE.CORTEX_USER and Cortex AI in your region.")
    st.stop()
if data.empty:
    st.info("No feedback in the last 90 days.")
    st.stop()

with st.sidebar:
    st.header("Filters")
    sources = st.multiselect("Source", sorted(data["SOURCE"].unique()))
    topics = st.multiselect("Topic", sorted(data["TOPIC"].unique()))

view = data
if sources:
    view = view[view["SOURCE"].isin(sources)]
if topics:
    view = view[view["TOPIC"].isin(topics)]
if view.empty:
    st.info("Nothing matches the filters.")
    st.stop()

recent = view[view["FEEDBACK_DATE"] > view["FEEDBACK_DATE"].max() - pd.Timedelta(days=30)]
earlier = view[view["FEEDBACK_DATE"] <= view["FEEDBACK_DATE"].max() - pd.Timedelta(days=30)]
neg_recent = (recent["MOOD"] == "Negative").mean() if len(recent) else 0
neg_earlier = (earlier["MOOD"] == "Negative").mean() if len(earlier) else None
k = st.columns(4)
k[0].metric("Comments", f"{len(view):,}")
k[1].metric("Average sentiment", f"{view['SENTIMENT'].mean():+.2f}", help="From -1 (very negative) to +1 (very positive).")
k[2].metric("Negative, last 30 days", f"{neg_recent:.0%}",
            f"{(neg_recent - neg_earlier) * 100:+.0f} pts" if neg_earlier is not None else None, delta_color="inverse")
k[3].metric("Most mentioned topic", view["TOPIC"].mode().iat[0])

weekly = (view.assign(WEEK=view["FEEDBACK_DATE"].dt.to_period("W").dt.start_time)
          .groupby(["WEEK", "MOOD"], as_index=False).size())
fig = px.bar(weekly, x="WEEK", y="size", color="MOOD", color_discrete_map=COLORS,
             category_orders={"MOOD": ["Negative", "Neutral", "Positive"]},
             labels={"size": "Comments", "WEEK": "", "MOOD": ""}, title="Comments per week by sentiment")
fig.update_layout(margin=dict(t=50, b=10))
st.plotly_chart(fig, width="stretch")

left, right = st.columns(2)
by_topic = view.groupby(["TOPIC", "MOOD"], as_index=False).size()
fig = px.bar(by_topic, x="size", y="TOPIC", color="MOOD", orientation="h", color_discrete_map=COLORS,
             category_orders={"MOOD": ["Negative", "Neutral", "Positive"]},
             labels={"size": "Comments", "TOPIC": "", "MOOD": ""}, title="Topics by sentiment")
fig.update_layout(margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")
by_source = view.groupby("SOURCE", as_index=False)["SENTIMENT"].mean().sort_values("SENTIMENT")
fig = px.bar(by_source, x="SENTIMENT", y="SOURCE", orientation="h", range_x=[-1, 1],
             color="SENTIMENT", color_continuous_scale=["#d62728", "#e5e7eb", "#2ca02c"], range_color=[-1, 1],
             labels={"SENTIMENT": "Average sentiment", "SOURCE": ""}, title="Sentiment by source")
fig.update_layout(margin=dict(t=50, b=10), coloraxis_showscale=False)
right.plotly_chart(fig, width="stretch")

st.subheader("What people complain about")
if st.button("Summarise the last 30 days' complaints"):
    try:
        st.info(complaint_summary())
    except Exception as e:
        st.warning(f"Could not summarise: {e}")
negative = view[view["MOOD"] == "Negative"].sort_values("FEEDBACK_DATE", ascending=False)
st.dataframe(negative[["FEEDBACK_DATE", "SOURCE", "TOPIC", "SENTIMENT", "FEEDBACK_TEXT"]].head(200).reset_index(drop=True),
             width="stretch", column_config={
                 "FEEDBACK_DATE": st.column_config.DateColumn("Date"), "SOURCE": "Source", "TOPIC": "Topic",
                 "SENTIMENT": st.column_config.NumberColumn("Sentiment", format="%.2f"), "FEEDBACK_TEXT": "Comment"})
st.download_button("Download scored feedback", view.drop(columns=["MOOD"]).to_csv(index=False), "feedback_scored.csv", "text/csv")
