"""Stateless error formatting helpers for the gateway.

This module provides utilities for formatting error responses in both
JSON and Server-Sent Events (SSE) formats. These are pure functions
with no state dependencies.
"""

from __future__ import annotations

import json
from typing import Mapping

from aiohttp import web


def json_error(
    code: str,
    message: str,
    *,
    status: int = 400,
    context: Mapping[str, object] | None = None,
    headers: Mapping[str, str] | None = None,
) -> web.Response:
    """Return a JSON error response in the canonical gateway format.

    Args:
        code: Machine-readable error code (e.g., "rate_limit", "invalid_request").
        message: Human-readable error description.
        status: HTTP status code (default 400).
        context: Additional context to include in the error payload.
        headers: Optional response headers.

    Returns:
        An aiohttp JSON response with the error payload.
    """
    payload = {"code": code, "message": message, "context": dict(context or {})}
    return web.json_response(payload, status=status, headers=headers or None)


def sse_error_event(code: str, message: str) -> bytes:
    """Format a Server-Sent Events error frame.

    Args:
        code: Machine-readable error code.
        message: Human-readable error description.

    Returns:
        UTF-8 encoded bytes representing an SSE error event.
    """
    data = json.dumps({"code": code, "message": message})
    return f"event: error\ndata: {data}\n\n".encode("utf-8")


__all__ = ["json_error", "sse_error_event"]
