import numpy as np


import plotly.graph_objects as go


def load_data():
    rng = np.random.default_rng(7)
    x_core = rng.normal(42.0, 9.0, size=280)
    y_core = 18.0 + 0.65 * x_core + rng.normal(0.0, 6.0, size=280)
    x_tail = rng.normal(68.0, 7.0, size=120)
    y_tail = 34.0 + 0.55 * x_tail + rng.normal(0.0, 5.5, size=120)
    xs = [round(float(v), 2) for v in np.concatenate([x_core, x_tail])]
    ys = [round(float(v), 2) for v in np.concatenate([y_core, y_tail])]
    return {"x": xs, "y": ys}


def value_table(data):
    x_arr = np.array(data["x"], dtype=float)
    y_arr = np.array(data["y"], dtype=float)
    return {
        "columns": ["Metric", "Payload (KB)", "Latency (ms)"],
        "rows": [
            ["Observations", len(x_arr), len(y_arr)],
            ["Median", round(float(np.median(x_arr)), 1), round(float(np.median(y_arr)), 1)],
            ["10th percentile", round(float(np.quantile(x_arr, 0.1)), 1), round(float(np.quantile(y_arr, 0.1)), 1)],
            ["90th percentile", round(float(np.quantile(x_arr, 0.9)), 1), round(float(np.quantile(y_arr, 0.9)), 1)],
        ],
    }


def make_after(data) -> go.Figure:
    fig = go.Figure(
        go.Scatter(
            x=data["x"],
            y=data["y"],
            mode="markers",
            name="Requests (n=400)",
            marker={"size": 7, "color": "#0072B2", "opacity": 0.28},
        )
    )
    fig.add_annotation(
        x=42,
        y=22,
        text="Primary cluster (280 requests)",
        showarrow=False,
        font={"size": 11, "color": "#334155"},
    )
    fig.add_annotation(
        x=72,
        y=86,
        text="Heavy-payload cluster (120 requests)",
        showarrow=False,
        font={"size": 11, "color": "#334155"},
    )
    fig.update_layout(
        template="simple_white",
        showlegend=False,
        xaxis_title="Payload size (KB)",
        yaxis_title="Response latency (ms)",
        xaxis_range=[10, 95],
        yaxis_range=[15, 95],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 60, "r": 24, "t": 28, "b": 48},
    )
    return fig


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