from math import exp


import plotly.graph_objects as go


def load_data():
    """Return fitted log odds coefficients and their standard errors."""
    return [
        ("Welcome email", 0.69, 0.20),
        ("Text reminder", 0.45, 0.18),
        ("Printed guide", 0.16, 0.16),
        ("Phone call", 0.80, 0.24),
        ("In-app tip", 0.30, 0.14),
    ]


def value_table(data):
    return {
        "columns": [
            "Intervention",
            "Log odds coefficient",
            "Standard error (log odds)",
            "Odds ratio",
            "Wald z",
        ],
        "rows": [
            [name, coef, se, round(exp(coef), 2), round(coef / se, 2)] for name, coef, se in data
        ],
    }


def _odds_ratio_figure(data, lower, upper, subtitle):
    names, coefficients, _ = zip(*data, strict=True)
    estimates = [exp(coef) for coef in coefficients]
    fig = go.Figure(
        go.Scatter(
            x=estimates,
            y=names,
            mode="markers",
            marker={"color": "#22628a", "size": 9},
            error_x={
                "type": "data",
                "symmetric": False,
                "array": [hi - value for hi, value in zip(upper, estimates, strict=True)],
                "arrayminus": [value - lo for value, lo in zip(estimates, lower, strict=True)],
                "color": "#22628a",
            },
            customdata=list(zip(lower, upper, strict=True)),
            hovertemplate=(
                "%{y}<br>Odds ratio %{x:.2f}<br>Bounds %{customdata[0]:.2f} to "
                "%{customdata[1]:.2f}<extra></extra>"
            ),
        )
    )
    fig.add_vline(x=1, line_color="#9ca3af", line_dash="dot")
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": "Enrollment after each intervention", "subtitle": {"text": subtitle}},
        xaxis={"title": "Odds ratio versus no intervention", "range": [0.5, 3.8]},
        yaxis_autorange="reversed",
        margin={"l": 116, "r": 24, "t": 76, "b": 60},
    )
    return fig


def make_before(data) -> go.Figure:
    lower = [exp(coef) - 1.96 * se for _, coef, se in data]
    upper = [exp(coef) + 1.96 * se for _, coef, se in data]
    return _odds_ratio_figure(data, lower, upper, "Odds ratios with unconverted log odds margins")


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