"""Histogram chart builders for HTML reports."""

from __future__ import annotations

import plotly.graph_objects as go

from .theme import DARK_THEME, FACTION_COLORS, to_html


def create_game_length_histogram(game_lengths: list[float]) -> str:
    """Create a histogram of game length distribution.

    Args:
        game_lengths: List of game lengths (turns)

    Returns:
        HTML string with embedded Plotly chart
    """
    if not game_lengths:
        return "<p>No game length data available</p>"

    avg_length = sum(game_lengths) / len(game_lengths)

    fig = go.Figure()

    fig.add_trace(
        go.Histogram(
            x=game_lengths,
            nbinsx=20,
            marker_color=FACTION_COLORS["obsidion"],
            opacity=0.8,
            hovertemplate="Turns: %{x}<br>Games: %{y}<extra></extra>",
        )
    )

    # Add average line
    fig.add_vline(
        x=avg_length,
        line_dash="dash",
        line_color=DARK_THEME["accent"],
        line_width=2,
        annotation_text=f"Avg: {avg_length:.1f}",
        annotation_position="top",
        annotation_font_color=DARK_THEME["accent"],
    )

    fig.update_layout(
        paper_bgcolor=DARK_THEME["bg_primary"],
        plot_bgcolor=DARK_THEME["bg_secondary"],
        font={"color": DARK_THEME["text_primary"]},
        xaxis={
            "title": "Game Length (Turns)",
            "gridcolor": DARK_THEME["grid"],
        },
        yaxis={
            "title": "Number of Games",
            "gridcolor": DARK_THEME["grid"],
        },
        height=300,
        margin={"t": 30, "b": 50, "l": 60, "r": 30},
        bargap=0.05,
    )

    return to_html(fig)
