"""Marketing performance — spend, conversions and return by channel and
campaign, with the funnel and efficiency over time."""

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

st.set_page_config(page_title="Marketing performance", layout="wide")

# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True runs on generated sample data. To use your own table, set
# DEMO = False and make the query return these columns (rename with AS).
DEMO = True
CAMPAIGNS_SQL = """
SELECT DATE, CAMPAIGN, CHANNEL, SPEND, IMPRESSIONS, CLICKS, CONVERSIONS, REVENUE
FROM {{DATABASE}}.{{SCHEMA}}.CAMPAIGN_DAILY
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = px.colors.qualitative.Safe


def demo_campaigns() -> pd.DataFrame:
    rng = np.random.default_rng(3)
    days = pd.date_range(end=pd.Timestamp.today().normalize(), periods=180, freq="D")
    channels = {  # cpm, ctr, cvr, order value
        "Paid search": (9, 0.045, 0.06, 140), "Social": (6, 0.012, 0.025, 110),
        "Display": (3, 0.004, 0.015, 120), "Email": (1, 0.03, 0.05, 95), "Affiliate": (4, 0.01, 0.04, 130),
    }
    campaigns = [("Spring launch", "Paid search"), ("Brand search", "Paid search"), ("Retargeting", "Display"),
                 ("Lookalikes", "Social"), ("Creators", "Social"), ("Newsletter", "Email"), ("Partners", "Affiliate")]
    rows = []
    for d in days:
        weekday = 0.8 if d.dayofweek >= 5 else 1.0
        for name, ch in campaigns:
            cpm, ctr, cvr, aov = channels[ch]
            imps = int(rng.uniform(20_000, 90_000) * weekday)
            clicks = rng.binomial(imps, ctr)
            conv = rng.binomial(clicks, cvr)
            rows.append((d, name, ch, round(imps / 1000 * cpm * rng.uniform(0.9, 1.1), 2), imps, clicks, conv,
                         round(conv * aov * rng.uniform(0.8, 1.2), 2)))
    return pd.DataFrame(rows, columns=["DATE", "CAMPAIGN", "CHANNEL", "SPEND", "IMPRESSIONS", "CLICKS", "CONVERSIONS", "REVENUE"])


@st.cache_data(ttl=600, show_spinner=False)
def load_campaigns() -> pd.DataFrame:
    if DEMO:
        df = demo_campaigns()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(CAMPAIGNS_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    df["DATE"] = pd.to_datetime(df["DATE"], errors="coerce")
    for c in ("SPEND", "IMPRESSIONS", "CLICKS", "CONVERSIONS", "REVENUE"):
        df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0)
    for c in ("CAMPAIGN", "CHANNEL"):
        df[c] = df[c].fillna("Unknown").astype(str)
    return df.dropna(subset=["DATE"])


def efficiency(frame: pd.DataFrame, by: list) -> pd.DataFrame:
    g = frame.groupby(by, as_index=False)[["SPEND", "IMPRESSIONS", "CLICKS", "CONVERSIONS", "REVENUE"]].sum()
    g["CTR"] = g["CLICKS"] / g["IMPRESSIONS"].replace(0, np.nan)
    g["CVR"] = g["CONVERSIONS"] / g["CLICKS"].replace(0, np.nan)
    g["CPA"] = g["SPEND"] / g["CONVERSIONS"].replace(0, np.nan)
    g["ROAS"] = g["REVENUE"] / g["SPEND"].replace(0, np.nan)
    return g


st.title("Marketing performance")
if DEMO:
    st.caption("Showing generated demo data — connect your own table in the DATA section.")

try:
    data = load_campaigns()
except Exception as e:
    st.error(f"Could not load campaign data: {e}")
    st.stop()
if data.empty:
    st.info("No campaign data yet.")
    st.stop()

with st.sidebar:
    st.header("Filters")
    days = st.select_slider("Period", options=[7, 14, 30, 60, 90, 180], value=30, format_func=lambda d: f"Last {d} days")
    channels = st.multiselect("Channel", sorted(data["CHANNEL"].unique()))

end = data["DATE"].max()
scope = data if not channels else data[data["CHANNEL"].isin(channels)]
current = scope[scope["DATE"] > end - pd.Timedelta(days=days)]
previous = scope[(scope["DATE"] <= end - pd.Timedelta(days=days)) & (scope["DATE"] > end - pd.Timedelta(days=2 * days))]
if current.empty:
    st.info("No data for these filters.")
    st.stop()

now, before = efficiency(current.assign(ALL=1), ["ALL"]).iloc[0], efficiency(previous.assign(ALL=1), ["ALL"])
before = before.iloc[0] if not before.empty else None


def change(key):
    if before is None or not before[key] or pd.isna(before[key]):
        return None
    return f"{(now[key] - before[key]) / before[key]:+.1%}"


k = st.columns(5)
k[0].metric("Spend", f"{now['SPEND']:,.0f}", change("SPEND"), delta_color="off")
k[1].metric("Conversions", f"{now['CONVERSIONS']:,.0f}", change("CONVERSIONS"))
k[2].metric("Cost per conversion", f"{now['CPA']:,.2f}", change("CPA"), delta_color="inverse")
k[3].metric("Revenue", f"{now['REVENUE']:,.0f}", change("REVENUE"))
k[4].metric("ROAS", f"{now['ROAS']:.2f}×", change("ROAS"))
st.caption(f"Last {days} days vs the {days} days before.")

weekly = efficiency(current.assign(WEEK=current["DATE"].dt.to_period("W").dt.start_time), ["WEEK", "CHANNEL"])
left, right = st.columns(2)
fig = px.bar(weekly, x="WEEK", y="SPEND", color="CHANNEL", color_discrete_sequence=COLORS,
             labels={"SPEND": "Spend", "WEEK": ""}, title="Spend by week")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

fig = px.line(weekly, x="WEEK", y="ROAS", color="CHANNEL", markers=True, color_discrete_sequence=COLORS,
              labels={"ROAS": "Return on ad spend", "WEEK": ""}, title="ROAS by week")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")

by_channel = efficiency(current, ["CHANNEL"])
left, right = st.columns(2)
fig = px.scatter(by_channel, x="CPA", y="ROAS", size="SPEND", color="CHANNEL", text="CHANNEL",
                 color_discrete_sequence=COLORS, size_max=50,
                 labels={"CPA": "Cost per conversion", "ROAS": "Return on ad spend"}, title="Channel efficiency")
fig.update_traces(textposition="top center")
fig.update_layout(showlegend=False, margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

fig = go.Figure(go.Funnel(y=["Impressions", "Clicks", "Conversions"],
                          x=[now["IMPRESSIONS"], now["CLICKS"], now["CONVERSIONS"]],
                          textinfo="value+percent previous", marker={"color": COLORS[:3]}))
fig.update_layout(title="Funnel", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")

st.subheader("Campaigns")
table = efficiency(current, ["CAMPAIGN", "CHANNEL"]).sort_values("SPEND", ascending=False).reset_index(drop=True)
st.dataframe(table, width="stretch", column_config={
    "SPEND": st.column_config.NumberColumn("Spend", format="localized"),
    "REVENUE": st.column_config.NumberColumn("Revenue", format="localized"),
    "IMPRESSIONS": st.column_config.NumberColumn("Impressions", format="compact"),
    "CLICKS": st.column_config.NumberColumn("Clicks", format="localized"),
    "CONVERSIONS": st.column_config.NumberColumn("Conversions", format="localized"),
    "CTR": st.column_config.NumberColumn("CTR", format="percent"),
    "CVR": st.column_config.NumberColumn("Conversion rate", format="percent"),
    "CPA": st.column_config.NumberColumn("Cost / conversion", format="%.2f"),
    "ROAS": st.column_config.ProgressColumn("ROAS", min_value=0, max_value=float(max(table["ROAS"].max(), 1)), format="%.2f"),
})
st.download_button("Download CSV", table.to_csv(index=False), "campaigns.csv", "text/csv")
