from __future__ import annotations

from http import HTTPStatus
from typing import Any


STATUS_CODES = {
    HTTPStatus.BAD_REQUEST: "bad_request",
    HTTPStatus.UNAUTHORIZED: "authentication_required",
    HTTPStatus.FORBIDDEN: "access_denied",
    HTTPStatus.NOT_FOUND: "not_found",
    HTTPStatus.CONFLICT: "conflict",
    HTTPStatus.INTERNAL_SERVER_ERROR: "internal_error",
    HTTPStatus.SERVICE_UNAVAILABLE: "service_unavailable",
}


def normalize_error_payload(
    payload: dict[str, Any], status: int | HTTPStatus, request_id: str,
) -> dict[str, Any]:
    if "error" not in payload:
        return payload
    status_value = HTTPStatus(int(status))
    message = str(payload.get("message") or payload.get("error") or status_value.phrase)
    return {
        **payload,
        "error": message,
        "code": str(payload.get("code") or STATUS_CODES.get(status_value) or "request_failed"),
        "message": message,
        "request_id": request_id,
    }
