from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
from fastapi.responses import JSONResponse, StreamingResponse

from app.config import settings
from app.services.ai_document_agent import (
    DocumentAiRunRequest,
    build_document_ai_config_payload,
    has_configured_openai_api_key,
    run_document_agent_stream,
    sdk_available,
)

router = APIRouter(prefix="/ai-agent")


def verify_internal_key(
    x_mnote_ai_key: Annotated[str | None, Header()] = None,
) -> None:
    expected = settings.mnote_ai_orchestrator_api_key.strip()
    if not expected:
        return
    if x_mnote_ai_key == expected:
        return
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid orchestrator key",
    )


@router.get("/health")
async def health() -> JSONResponse:
    return JSONResponse(
        {
            "ok": True,
            "bridge": "openai_agents_python",
            "sdkAvailable": sdk_available(),
            "openaiConfigured": has_configured_openai_api_key(),
            "bridgeRuntimeMode": "local_runtime",
        }
    )


@router.post("/document/run")
async def run_document(
    request: Request,
    payload: DocumentAiRunRequest,
    _: None = Depends(verify_internal_key),
) -> StreamingResponse:
    stream = run_document_agent_stream(
        payload,
        source_headers={key.lower(): value for key, value in request.headers.items()},
    )
    return StreamingResponse(stream, media_type="text/event-stream")


@router.get("/document/config")
async def get_document_config(
    _: None = Depends(verify_internal_key),
) -> JSONResponse:
    return JSONResponse(build_document_ai_config_payload())
