import logging
from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field, ConfigDict
from typing import List, Optional

from src.services.agent_engine import AgentScopeService
from src.utils.errors import BusinessException, ErrorCode
from src.auth.dependencies import get_current_user, UserAuth

router = APIRouter(prefix="/chat", tags=["chat"])
logger = logging.getLogger(__name__)

class Message(BaseModel):
    role: str
    content: str

class ChatCompletionRequest(BaseModel):
    messages: List[Message]
    model: Optional[str] = None
    stream: bool = True
    temperature: Optional[float] = 0.7
    max_tokens: Optional[int] = Field(None, alias="maxTokens")
    
    model_config = ConfigDict(populate_by_name=True)

@router.post("/completions")
async def chat_completions(
    request: ChatCompletionRequest,
    current_user: UserAuth = Depends(get_current_user)
):
    """
    OpenAI-compatible chat completion endpoint.
    Supports streaming and non-streaming modes.
    Now integrated with AgentScope.

    Raises:
        BusinessException: Chat completion failed
    """
    if not request.stream:
        raise BusinessException(
            ErrorCode.INVALID_PARAMETER,
            "Non-stream mode is not supported",
            {"field": "stream", "expected": True}
        )

    messages_payload = [m.model_dump() for m in request.messages]

    try:
        agent_service = AgentScopeService(user_id=current_user.id)
        return StreamingResponse(
            agent_service.stream_chat(messages_payload),
            media_type="text/event-stream"
        )
    except Exception as e:
        logger.error(f"AgentScope service error: {e}", exc_info=True)
        raise BusinessException(
            ErrorCode.GENERATION_FAILED,
            "Chat completion failed",
            {"reason": str(e)}
        )
