#!/usr/bin/env catnip
# Dashboard Plotly autonome exporté en HTML
#
# Objectif:
# - construire un mini dashboard sans pandas
# - montrer l'interop Python directe via plotly.graph_objects
# - produire un HTML ouvrable localement
#
# DEPS: plotly

go = import('plotly.graph_objects')
pathlib = import('pathlib')
tempfile = import('tempfile')
webbrowser = import('webbrowser')

months = list("Jan", "Fev", "Mar", "Avr", "Mai", "Juin")
revenue = list(42, 48, 51, 49, 58, 64)
orders = list(120, 132, 145, 140, 162, 181)
conversion = list(2.8, 3.1, 3.0, 2.9, 3.4, 3.8)

fig = go.Figure()

fig.add_trace(go.Bar(
        name="CA (kEUR)",
        x=months,
        y=revenue,
        marker=dict(color="#1f77b4"),
        yaxis="y",
    ))

fig.add_trace(go.Scatter(
        name="Commandes",
        x=months,
        y=orders,
        mode="lines+markers",
        line=dict(color="#ff7f0e", width=3),
        marker=dict(size=9),
        yaxis="y2",
    ))

fig.add_trace(go.Scatter(
        name="Conversion (%)",
        x=months,
        y=conversion,
        mode="lines+markers",
        line=dict(color="#2ca02c", width=3, dash="dot"),
        marker=dict(size=8),
        yaxis="y3",
    ))

fig.update_layout(
    title="Dashboard ventes Catnip x Plotly",
    template="plotly_white",
    width=980,
    height=560,
    hovermode="x unified",
    legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0),
    margin=dict(l=60, r=60, t=90, b=50),
    xaxis=dict(title="Mois"),
    yaxis=dict(
        title="CA (kEUR)",
        title_font=dict(color="#1f77b4"),
        tickfont=dict(color="#1f77b4"),
    ),
    yaxis2=dict(
        title="Commandes",
        title_font=dict(color="#ff7f0e"),
        tickfont=dict(color="#ff7f0e"),
        anchor="x",
        overlaying="y",
        side="right",
    ),
    yaxis3=dict(
        title="Conversion (%)",
        title_font=dict(color="#2ca02c"),
        tickfont=dict(color="#2ca02c"),
        anchor="free",
        overlaying="y",
        side="right",
        position=0.93,
    ),
    annotations=list(
        dict(
            x="Juin",
            y=64,
            text="Pic de CA",
            showarrow=True,
            arrowhead=2,
            ax=-40,
            ay=-45,
        ),
    ),
)

out_dir = pathlib.Path(tempfile.gettempdir()) / "catnip_plotly_examples"
out_dir.mkdir(parents=True, exist_ok=True)
out_file = out_dir / "plotly_sales_dashboard.html"

fig.write_html(str(out_file), include_plotlyjs="cdn")

print("Fichier HTML :", out_file)
print("CA total     :", sum(revenue), "kEUR")
print("Commandes    :", sum(orders))
print("Conversion max:", max(conversion), "%")

webbrowser.open(out_file.as_uri())