from __future__ import annotations

from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse, StreamingResponse

from ai_orchestrator.schemas.openai_compat import ChatCompletionRequest, ChatCompletionResponse
from ai_orchestrator.services.openai_compat_service import OpenAICompatHTTPError, OpenAICompatService

router = APIRouter(prefix="/v1", tags=["openai-compatible"])


def get_openai_compat_service(request: Request) -> OpenAICompatService:
    return request.app.state.openai_compat_service


def require_openai_compat_auth(
    request: Request,
    service: OpenAICompatService = Depends(get_openai_compat_service),
) -> None:
    service.require_api_key(request.headers.get("Authorization"))


@router.get("/models", dependencies=[Depends(require_openai_compat_auth)])
async def list_models(
    service: OpenAICompatService = Depends(get_openai_compat_service),
):
    return service.list_models()


@router.get("/models/{model_id}", dependencies=[Depends(require_openai_compat_auth)])
async def get_model(
    model_id: str,
    service: OpenAICompatService = Depends(get_openai_compat_service),
):
    return service.get_model(model_id)


@router.post(
    "/chat/completions",
    dependencies=[Depends(require_openai_compat_auth)],
    response_model=ChatCompletionResponse,
)
async def create_chat_completion(
    request: Request,
    payload: ChatCompletionRequest,
    service: OpenAICompatService = Depends(get_openai_compat_service),
):
    if payload.stream:
        return StreamingResponse(
            service.stream_chat_completion(payload, headers=request.headers),
            media_type="text/event-stream",
        )
    return await service.create_chat_completion(payload, headers=request.headers)


def openai_compat_error_response(exc: OpenAICompatHTTPError) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code,
        content=exc.to_payload().model_dump(exclude_none=True),
    )
