import plotly.graph_objects as go


TITLE = "Museum attendance by site"


COLUMNS = ["Site", "Reporting coverage", "Visits"]


def load_data():
    return [
        ("History Hall", "History Hall and City Archive combined", 1280),
        ("City Archive", "History Hall and City Archive combined", None),
        ("Art House", "Art House only", 870),
        ("Science Center", "Science Center only", 1120),
        ("Design Studio", "Design Studio only", 640),
    ]


def value_table(data):
    return {"columns": COLUMNS, "rows": [list(row) for row in data]}


def table_trace(columns, rows, align, widths, *, row_height=28, header_height=34, fill="#ffffff"):
    return go.Table(
        columnwidth=widths,
        header={
            "values": [f"<b>{column}</b>" for column in columns],
            "align": align,
            "height": header_height,
            "fill": {"color": "#eef2f6"},
            "line": {"width": 0},
            "font": {"color": "#1f2937", "size": 13},
        },
        cells={
            "values": list(zip(*rows, strict=True)),
            "align": align,
            "height": row_height,
            "fill": {"color": fill},
            "line": {"width": 0},
            "font": {"color": "#1f2937", "size": 13},
        },
    )


def style_table(fig, title, *, height=280, top=60, bottom=16):
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": title, "x": 0.04, "xanchor": "left"},
        height=height,
        margin={"l": 24, "r": 24, "t": top, "b": bottom},
    )
    return fig


def table_note(fig, text, *, y=0, anchor="top", shift=-8):
    fig.add_annotation(
        text=text,
        x=0,
        y=y,
        xref="paper",
        yref="paper",
        xanchor="left",
        yanchor=anchor,
        yshift=shift,
        align="left",
        showarrow=False,
        font={"size": 12, "color": "#475569"},
    )


def make_after(data) -> go.Figure:
    rows = [
        (
            site,
            f"<b>{visits:,} combined [a]</b>"
            if coverage.endswith("combined") and visits is not None
            else "Included in [a]"
            if visits is None
            else f"{visits:,}",
        )
        for site, coverage, visits in data
    ]
    fig = go.Figure(table_trace(["Site", "Visits"], rows, ["left", "right"], [2, 1]))
    table_note(
        fig,
        "[a] Joint count for History Hall and City Archive.<br>"
        "Separate site counts start at Art House.",
    )
    return style_table(fig, TITLE, height=300, bottom=63)


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