"""Recommendations page: plain-English budget advice."""

import streamlit as st

from frontend import api_client


def show_recommendations_page():
    project = st.session_state.get("current_project")
    if not project:
        st.warning("No project selected")
        return

    st.title(f"Recommendations: {project['name']}")

    if st.button("< Back to Results"):
        st.session_state["page"] = "results"
        st.rerun()

    # Fetch latest run
    resp = api_client.get(f"/projects/{project['id']}/runs/latest")
    if resp.status_code != 200:
        st.warning("No model results yet.")
        return

    run = resp.json()
    if run["status"] != "completed":
        st.info(f"Model status: {run['status']}")
        return

    # Executive summary
    if run.get("summary_text"):
        st.info(run["summary_text"])

    if run.get("expected_lift_pct"):
        st.metric(
            "Expected Improvement from Reallocation",
            f"+{run['expected_lift_pct']:.1f}%",
        )

    st.divider()

    # Recommendation cards
    recommendations = run.get("recommendations", [])
    if not recommendations:
        st.success("Your current allocation is close to optimal. No major changes recommended.")
        return

    for rec in recommendations:
        action = rec["action"]
        color = "green" if action == "INCREASE" else "red"
        sign = "+" if action == "INCREASE" else "-"

        with st.container():
            st.markdown(
                f"### #{rec['rank']} :{color}[{action}] {rec['channel']}"
            )
            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric("Change", f"{sign}${rec['change_amount']:,.0f}/week")
            with col2:
                st.metric("Current", f"${rec['current_spend']:,.0f}/week")
            with col3:
                st.metric("Optimal", f"${rec['optimal_spend']:,.0f}/week")

            st.caption(f"ROAS: {rec['roas']:.1f}x | {rec['reason']}")
            st.divider()
