import plotly.graph_objects as go


TITLE = "Heat and electricity demand"


COLUMNS = ["Term", "Coefficient"]


def load_data():
    return [
        ("Intercept", 12.0),
        ("Degrees above 20 °C", 0.4),
        ("Degrees above 20 °C, squared", 0.025),
        ("Weekend", -2.0),
        ("Weekend interaction with degrees above 20 °C", -0.2),
    ]


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 make_after(data) -> go.Figure:
    coefficients = dict(data)
    rows = []
    for temperature in (20, 22, 24, 26, 28, 30):
        degrees = temperature - 20
        weekday = (
            coefficients["Intercept"]
            + coefficients["Degrees above 20 °C"] * degrees
            + coefficients["Degrees above 20 °C, squared"] * degrees**2
        )
        weekend = (
            weekday
            + coefficients["Weekend"]
            + coefficients["Weekend interaction with degrees above 20 °C"] * degrees
        )
        rows.append((temperature, f"{weekday:.1f}", f"{weekend:.1f}"))
    columns = ["Temperature (°C)", "Weekday (MWh)", "Weekend (MWh)"]
    return style_table(
        go.Figure(table_trace(columns, rows, ["right"] * 3, [1, 1, 1])), TITLE, height=300
    )


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