import plotly.graph_objects as go


def load_data():
    return [
        ("Jan", 820, 76, "Original"),
        ("Feb", 800, 74, "Original"),
        ("Mar", 810, 75, "Original"),
        ("Apr", 620, 51, "Replacement"),
        ("May", 600, 49, "Replacement"),
        ("Jun", 610, 50, "Replacement"),
    ]


def value_table(data):
    return {
        "columns": ["Month", "Electricity use (kWh)", "Pump runtime (hours)", "Controller"],
        "rows": [list(row) for row in data],
    }


def pump_energy(data):
    months, energy, _, _ = zip(*data, strict=True)
    return go.Scatter(
        x=months,
        y=energy,
        mode="lines+markers",
        line_color="#356890",
        hovertemplate="%{x}: %{y} kWh<extra></extra>",
    )


def make_after(data) -> go.Figure:
    months, _, runtime, controllers = zip(*data, strict=True)
    fig = go.Figure(pump_energy(data))
    fig.add_scatter(
        x=months,
        y=runtime,
        mode="lines+markers",
        line_color="#356890",
        yaxis="y2",
        hovertemplate="%{x}: %{y} hours<extra></extra>",
    )
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title="Pump runtime and electricity use fell after the controller change",
        yaxis={"title": "Electricity use (kWh)", "range": [550, 860], "domain": [0, 0.42]},
        yaxis2={"title": "Runtime (hours)", "range": [42, 82], "domain": [0.58, 1]},
        showlegend=False,
        height=500,
        margin={"l": 86, "r": 36, "t": 76, "b": 54},
    )
    first_replacement = months[controllers.index("Replacement")]
    fig.add_shape(
        type="line",
        x0=first_replacement,
        x1=first_replacement,
        xref="x",
        y0=0,
        y1=1,
        yref="paper",
        layer="below",
        line={"color": "#64748b", "dash": "dot", "width": 1},
    )
    fig.add_annotation(
        x=first_replacement,
        y=1,
        xref="x",
        yref="paper",
        text="Controller replaced",
        showarrow=False,
        xanchor="left",
        yanchor="bottom",
        xshift=6,
    )
    return fig


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