"""Gauge and pie chart builders for HTML reports."""

from __future__ import annotations

from typing import TYPE_CHECKING

import plotly.graph_objects as go

from .theme import DARK_THEME, FACTION_COLORS, to_html

if TYPE_CHECKING:
    from ..loaders.validation import DeckStats


def create_health_gauge(score: float) -> str:
    """Create a health score gauge chart.

    Args:
        score: Health score from 0-100

    Returns:
        HTML string with embedded Plotly chart
    """
    # Determine color based on score
    if score >= 75:
        bar_color = DARK_THEME["success"]
    elif score >= 50:
        bar_color = DARK_THEME["warning"]
    else:
        bar_color = DARK_THEME["danger"]

    fig = go.Figure(
        go.Indicator(
            mode="gauge+number",
            value=score,
            domain={"x": [0, 1], "y": [0, 1]},
            title={"text": "Balance Health", "font": {"color": DARK_THEME["text_primary"]}},
            number={"suffix": "", "font": {"color": DARK_THEME["text_primary"], "size": 48}},
            gauge={
                "axis": {
                    "range": [0, 100],
                    "tickwidth": 1,
                    "tickcolor": DARK_THEME["text_secondary"],
                    "tickfont": {"color": DARK_THEME["text_secondary"]},
                },
                "bar": {"color": bar_color},
                "bgcolor": DARK_THEME["bg_card"],
                "borderwidth": 2,
                "bordercolor": DARK_THEME["text_secondary"],
                "steps": [
                    {"range": [0, 50], "color": "rgba(220, 53, 69, 0.2)"},
                    {"range": [50, 75], "color": "rgba(255, 193, 7, 0.2)"},
                    {"range": [75, 100], "color": "rgba(0, 210, 106, 0.2)"},
                ],
                "threshold": {
                    "line": {"color": DARK_THEME["accent"], "width": 4},
                    "thickness": 0.75,
                    "value": score,
                },
            },
        )
    )

    fig.update_layout(
        paper_bgcolor=DARK_THEME["bg_primary"],
        font={"color": DARK_THEME["text_primary"]},
        height=250,
        margin={"t": 50, "b": 20, "l": 30, "r": 30},
    )

    return to_html(fig)


def create_faction_distribution(deck_stats: list[DeckStats]) -> str:
    """Create a faction distribution donut chart.

    Args:
        deck_stats: List of DeckStats objects

    Returns:
        HTML string with embedded Plotly chart
    """
    # Count decks by faction and calculate average win rate
    faction_data = {}
    for d in deck_stats:
        if d.faction not in faction_data:
            faction_data[d.faction] = {"count": 0, "total_wr": 0.0}
        faction_data[d.faction]["count"] += 1
        faction_data[d.faction]["total_wr"] += d.win_rate

    factions = list(faction_data.keys())
    counts = [faction_data[f]["count"] for f in factions]
    avg_wr = [faction_data[f]["total_wr"] / faction_data[f]["count"] * 100 for f in factions]
    colors = [FACTION_COLORS.get(f, DARK_THEME["text_secondary"]) for f in factions]

    fig = go.Figure(
        data=[
            go.Pie(
                labels=[f.title() for f in factions],
                values=counts,
                hole=0.5,
                marker_colors=colors,
                textinfo="label+percent",
                textposition="outside",
                hovertemplate="<b>%{label}</b><br>Decks: %{value}<br>Avg Win Rate: %{customdata:.1f}%<extra></extra>",
                customdata=avg_wr,
            )
        ]
    )

    fig.update_layout(
        title={"text": "Faction Distribution", "font": {"color": DARK_THEME["text_primary"]}},
        paper_bgcolor=DARK_THEME["bg_primary"],
        font={"color": DARK_THEME["text_primary"]},
        height=300,
        margin={"t": 50, "b": 30, "l": 30, "r": 30},
        showlegend=False,
        annotations=[
            {
                "text": f"{len(deck_stats)}<br>Decks",
                "x": 0.5,
                "y": 0.5,
                "font_size": 16,
                "font_color": DARK_THEME["text_primary"],
                "showarrow": False,
            }
        ],
    )

    return to_html(fig)
