from __future__ import annotations

from fastapi import Request


def request_client_ip(request: Request) -> str:
    """提取客户端 IP，优先读取代理转发头。"""
    forwarded_for = request.headers.get("x-forwarded-for", "")
    if forwarded_for:
        return forwarded_for.split(",", 1)[0].strip()
    return request.client.host if request.client else ""


def request_user_agent(request: Request) -> str:
    """提取浏览器 User-Agent。"""
    return request.headers.get("user-agent", "")


def operation_request_meta(request: Request) -> dict[str, str]:
    """生成操作日志使用的请求元信息。"""
    return {
        "ip_address": request_client_ip(request),
        "user_agent": request_user_agent(request),
    }
