import plotly.graph_objects as go


Row = tuple[str, str, int]


def value_table(data: list[Row]) -> dict[str, list]:
    return {"columns": ["From", "To", "Parcels"], "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": "Parcel flow through sorting", "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 [
        ("Web orders", "Sorting", 60),
        ("Store orders", "Sorting", 40),
        ("Sorting", "City route", 65),
        ("Sorting", "Rural route", 25),
        ("Sorting", "Returns", 10),
    ]


def make_after(data: list[Row]) -> go.Figure:
    sources, destinations, counts = zip(*data, strict=True)
    labels = list(dict.fromkeys((*sources, *destinations)))
    indices = {label: index for index, label in enumerate(labels)}
    terminal_counts = {end: count for _, end, count in data if end not in sources}
    node_labels = [
        f"{label} ({terminal_counts[label]})" if label in terminal_counts else label
        for label in labels
    ]
    fig = go.Figure(
        go.Sankey(
            node={"label": node_labels, "color": "#226391", "pad": 24, "thickness": 18},
            link={
                "source": [indices[source] for source in sources],
                "target": [indices[destination] for destination in destinations],
                "value": counts,
                "color": "rgba(34, 99, 145, 0.32)",
                "hovertemplate": (
                    "%{source.label} to %{target.label}: %{value} parcels<extra></extra>"
                ),
            },
        )
    )
    return _style_figure(fig, height=360)


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