"""Plotly layout transformer for WCAG conformance."""

from a11yviz._rules import check_level, load_rules


def layout(fig, level: str = "AA"):
    """Apply accessible layout to a plotly Figure.

    Sets fonts, axis styling, hover-label colours, and legend position to
    meet WCAG 2.1 contrast and resize-text criteria. Returns the same
    Figure so it stays usable in a fluent chain.
    """
    try:
        import plotly.graph_objects as go  # noqa: F401
    except ImportError as e:
        raise ImportError(
            "layout() requires plotly. Install with: pip install a11yviz[plotly]"
        ) from e

    level = check_level(level)
    rules = load_rules()
    fz = rules["font_size"][level]
    tt = rules["tooltip"]

    body = dict(family=tt["font"], size=fz["body"], color="#222")
    title = dict(family=tt["font"], size=fz["title"], color="#222")
    hover = dict(family=tt["font"], size=tt["size"], color=tt["text"])
    axis = dict(
        tickfont=body, title_font=title,
        gridcolor="#e5e5e5", zerolinecolor="#c0c0c0",
    )

    fig.update_layout(
        autosize=True,
        font=body,
        margin=dict(t=30, b=60, l=90, r=30, autoexpand=True),
        paper_bgcolor="rgba(0,0,0,0)",
        plot_bgcolor="rgba(0,0,0,0)",
        hoverlabel=dict(
            bgcolor=tt["bg"], bordercolor=tt["border"],
            font=hover, align="left", namelength=-1,
        ),
        legend=dict(
            orientation="v", x=1.02, xanchor="left",
            y=0.5, yanchor="middle", font=body, title=dict(font=title),
        ),
        xaxis=axis, yaxis=axis,
    )
    return fig
