"""
OpenAI API 端点

- /v1/chat/completions - OpenAI Chat API
- /v1/responses - OpenAI Responses API (CLI)

注意: /v1/models 端点由 models.py 统一处理，根据请求头返回对应格式
"""

from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session

from src.api.base.pipeline import ApiRequestPipeline
from src.api.handlers.openai import OpenAIChatAdapter
from src.api.handlers.openai_cli import OpenAICliAdapter
from src.core.api_format_metadata import get_api_format_definition
from src.core.enums import APIFormat
from src.database import get_db

_openai_def = get_api_format_definition(APIFormat.OPENAI)
router = APIRouter(tags=["OpenAI API"], prefix=_openai_def.path_prefix)
pipeline = ApiRequestPipeline()


@router.post("/v1/chat/completions")
async def create_chat_completion(
    http_request: Request,
    db: Session = Depends(get_db),
):
    """
    OpenAI Chat Completions API

    兼容 OpenAI Chat Completions API 格式的代理接口。

    **认证方式**: Bearer Token（API Key 或 JWT Token）

    **请求格式**:
    ```json
    {
        "model": "gpt-4",
        "messages": [{"role": "user", "content": "Hello"}],
        "stream": false
    }
    ```

    **支持的参数**: model, messages, stream, temperature, max_tokens 等标准 OpenAI 参数
    """
    adapter = OpenAIChatAdapter()
    return await pipeline.run(
        adapter=adapter,
        http_request=http_request,
        db=db,
        mode=adapter.mode,
        api_format_hint=adapter.allowed_api_formats[0],
    )


@router.post("/v1/responses")
async def create_responses(
    http_request: Request,
    db: Session = Depends(get_db),
):
    """
    OpenAI Responses API (CLI)

    兼容 OpenAI Codex CLI 使用的 Responses API 格式，请求透传到上游。

    **认证方式**: Bearer Token（API Key 或 JWT Token）
    """
    adapter = OpenAICliAdapter()
    return await pipeline.run(
        adapter=adapter,
        http_request=http_request,
        db=db,
        mode=adapter.mode,
        api_format_hint=adapter.allowed_api_formats[0],
    )
