from math import cos, pi, sin


import plotly.graph_objects as go


Row = tuple[str, str, int]


def value_table(data: list[Row]) -> dict[str, list]:
    return {"columns": ["Team A", "Team B", "Shared projects"], "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": "Shared projects between teams", "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 [
        ("Design", "Support", 2),
        ("Design", "Sales", 4),
        ("Design", "Finance", 0),
        ("Design", "Research", 6),
        ("Design", "Product", 5),
        ("Support", "Sales", 5),
        ("Support", "Finance", 1),
        ("Support", "Research", 2),
        ("Support", "Product", 3),
        ("Sales", "Finance", 3),
        ("Sales", "Research", 1),
        ("Sales", "Product", 4),
        ("Finance", "Research", 2),
        ("Finance", "Product", 1),
        ("Research", "Product", 5),
    ]


def _team_names(data: list[Row]) -> list[str]:
    return list(dict.fromkeys(team for left, right, _ in data for team in (left, right)))


def make_before(data: list[Row]) -> go.Figure:
    teams = _team_names(data)
    angles = [pi / 2 - 2 * pi * index / len(teams) for index in range(len(teams))]
    positions = dict(zip(teams, [(cos(angle), sin(angle)) for angle in angles], strict=True))
    fig = go.Figure()
    for left, right, count in data:
        if count == 0:
            continue
        x, y = zip(positions[left], positions[right], strict=True)
        fig.add_scatter(
            x=x,
            y=y,
            mode="lines",
            line={"color": "#7898ad", "width": 1 + count / 2},
            hoverinfo="skip",
        )
        fig.add_annotation(
            x=sum(x) / 2,
            y=sum(y) / 2,
            text=str(count),
            showarrow=False,
            bgcolor="#ffffff",
        )
    x, y = zip(*(positions[team] for team in teams), strict=True)
    fig.add_scatter(
        x=x,
        y=y,
        mode="markers",
        marker={"color": "#226391", "size": 12},
        text=teams,
        hovertemplate="%{text}<extra></extra>",
    )
    for team, (team_x, team_y) in positions.items():
        fig.add_annotation(x=1.23 * team_x, y=1.23 * team_y, text=team, showarrow=False)
    return _style_figure(
        fig,
        xaxis={"visible": False, "range": [-1.55, 1.55], "constrain": "domain"},
        yaxis={"visible": False, "range": [-1.45, 1.45], "scaleanchor": "x"},
    )


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