"""History page — closed-trade table with filters and CSV export."""

from __future__ import annotations

import io
import os
from datetime import UTC, datetime, timedelta
from pathlib import Path

import pandas as pd
import streamlit as st

from cerbero_bite.gui.data_layer import (
    DEFAULT_DB_PATH,
    compute_kpis,
    humanize_dt,
    load_closed_positions,
)


def _resolve_db() -> Path:
    return Path(os.environ.get("CERBERO_BITE_GUI_DB", DEFAULT_DB_PATH))


def _date_window() -> tuple[datetime | None, datetime | None]:
    presets = {
        "Tutto lo storico": (None, None),
        "Ultimi 7 giorni": (datetime.now(UTC) - timedelta(days=7), None),
        "Ultimi 30 giorni": (datetime.now(UTC) - timedelta(days=30), None),
        "Ultimi 90 giorni": (datetime.now(UTC) - timedelta(days=90), None),
        "Da inizio anno": (
            datetime(datetime.now(UTC).year, 1, 1, tzinfo=UTC),
            None,
        ),
    }
    pick = st.selectbox("Finestra", list(presets.keys()), index=0)
    return presets[pick]


def render() -> None:
    st.title("📜 Storico")
    st.caption(
        "Trade chiusi con filtri, striscia KPI ed esportazione CSV."
    )

    db_path = _resolve_db()
    start, end = _date_window()
    positions = load_closed_positions(db_path=db_path, start=start, end=end)

    # Sotto-filtri per motivo di chiusura e segno P&L
    reason_options = sorted(
        {p.close_reason or "(sconosciuto)" for p in positions}
    )
    chosen_reasons = st.multiselect(
        "Motivi di chiusura",
        options=reason_options,
        default=reason_options,
    )
    pnl_filter = st.radio(
        "Filtro P&L",
        options=["tutti", "vincenti", "perdenti"],
        horizontal=True,
        index=0,
    )

    filtered = []
    for p in positions:
        reason = p.close_reason or "(sconosciuto)"
        if reason not in chosen_reasons:
            continue
        if pnl_filter == "vincenti" and (p.pnl_usd is None or p.pnl_usd <= 0):
            continue
        if pnl_filter == "perdenti" and (p.pnl_usd is None or p.pnl_usd >= 0):
            continue
        filtered.append(p)

    # Striscia KPI
    kpis = compute_kpis(filtered)
    cols = st.columns(6)
    cols[0].metric("Trade", kpis.n_trades)
    cols[1].metric("Win rate", f"{kpis.win_rate:.0%}")
    cols[2].metric("P&L totale", f"${float(kpis.total_pnl_usd):+.2f}")
    cols[3].metric("Vittoria media", f"${float(kpis.avg_win_usd):+.2f}")
    cols[4].metric("Perdita media", f"${float(kpis.avg_loss_usd):+.2f}")
    cols[5].metric("Edge / trade", f"${float(kpis.edge_per_trade_usd):+.2f}")

    st.divider()

    if not filtered:
        st.info("Nessun trade corrisponde ai filtri correnti.")
        return

    # DataFrame per visualizzazione + esportazione
    rows = []
    for p in filtered:
        days_held = (
            (p.closed_at - p.opened_at).days
            if p.opened_at and p.closed_at
            else None
        )
        rows.append(
            {
                "proposal_id": str(p.proposal_id)[:8],
                "spread": p.spread_type,
                "asset": p.asset,
                "n. contratti": p.n_contracts,
                "strike short": float(p.short_strike),
                "strike long": float(p.long_strike),
                "credito (USD)": float(p.credit_usd),
                "max perdita (USD)": float(p.max_loss_usd),
                "P&L (USD)": (
                    float(p.pnl_usd) if p.pnl_usd is not None else None
                ),
                "motivo chiusura": p.close_reason or "(sconosciuto)",
                "giorni tenuta": days_held,
                "aperta il": humanize_dt(p.opened_at),
                "chiusa il": humanize_dt(p.closed_at),
                "scadenza": humanize_dt(p.expiry),
            }
        )
    df = pd.DataFrame(rows)
    st.dataframe(df, use_container_width=True, hide_index=True)

    # Esportazione CSV
    buf = io.StringIO()
    df.to_csv(buf, index=False)
    st.download_button(
        "⬇ Scarica CSV",
        data=buf.getvalue(),
        file_name=f"cerbero_bite_storico_{datetime.now(UTC).date()}.csv",
        mime="text/csv",
    )


render()
