"""
HTTP 工具函数：统一错误处理、请求构建。
"""

from __future__ import annotations

from typing import Any

import httpx

from cmdc.exceptions import (
    AuthError,
    BadRequestError,
    CMDCError,
    RateLimitError,
    SessionCreateError,
    SessionNotFoundError,
)


def raise_for_status(response: httpx.Response) -> None:
    """根据响应状态码抛出对应的 SDK 异常。"""
    if response.is_success:
        return

    status = response.status_code
    try:
        body = response.json()
        message = body.get("message", response.text)
    except Exception:
        message = response.text

    if status == 401:
        raise AuthError(message, status_code=401)
    if status == 404:
        raise SessionNotFoundError(message, status_code=404)
    if status == 422:
        raise SessionCreateError(message, status_code=422)
    if status == 429:
        retry_after: int | None = None
        try:
            retry_after = int(response.headers.get("Retry-After", 0)) or None
        except (ValueError, TypeError):
            pass
        raise RateLimitError(message, retry_after=retry_after)
    if status == 400:
        raise BadRequestError(message, status_code=400)

    raise CMDCError(message, status_code=status)
