import plotly.graph_objects as go


Row = tuple[str, str, int]


def value_table(data: list[Row]) -> dict[str, list]:
    return {"columns": ["Division", "Team", "Training hours"], "rows": [list(row) for row in data]}


def _style_figure(fig: go.Figure, **layout: object) -> go.Figure:
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": "Training hours by division and team", "x": 0.02, "xanchor": "left"},
        margin={"l": 72, "r": 32, "t": 84, "b": 64},
        showlegend=False,
        **layout,
    )
    return fig


def load_data() -> list[Row]:
    return [
        ("Operations", "Dispatch", 42),
        ("Operations", "Fleet", 24),
        ("Operations", "Stores", 15),
        ("Services", "Intake", 29),
        ("Services", "Support", 34),
        ("Services", "Billing", 17),
    ]


def make_after(data: list[Row]) -> go.Figure:
    divisions, teams, hours = zip(*data, strict=True)
    groups = list(dict.fromkeys(divisions))
    totals = [sum(row[2] for row in data if row[0] == group) for group in groups]
    colors = {"Operations": "#c7dceb", "Services": "#e8d6bd"}
    fig = go.Figure(
        go.Treemap(
            labels=[*groups, *teams],
            parents=[""] * len(groups) + list(divisions),
            values=[*totals, *hours],
            branchvalues="total",
            pathbar={"visible": False},
            marker={"colors": [colors[group] for group in (*groups, *divisions)]},
            textfont={"color": "#1f2937"},
            texttemplate="%{label}<br>%{value} h",
            hovertemplate="%{label}: %{value} hours<extra></extra>",
        )
    )
    return _style_figure(fig, height=395, uniformtext={"minsize": 11, "mode": "hide"})


if __name__ == "__main__":
    print(make_after(load_data()).to_json())
