from __future__ import annotations

from app.core.exceptions import AppError
from app.modules.api.application.request_service import RequestService
from app.schemas.agent_api import AgentRequestCreateRequest, AgentRequestQueuedResponse, AgentRequestStateResponse
from app.schemas.common import ModuleName


class RequestController:
    def __init__(self, service: RequestService) -> None:
        self._service = service

    async def create_request(self, request: AgentRequestCreateRequest) -> AgentRequestQueuedResponse:
        item = await self._service.create(request.session_id, request.message, request.process_version)
        return AgentRequestQueuedResponse(
            request_id=item.request_id,
            session_id=item.session_id,
            status=item.status.value,
            stream_url=f"/api/agent/streams/{item.request_id}",
        )

    def get_request(self, request_id: str) -> AgentRequestStateResponse:
        item = self._service.get(request_id)
        if item is None:
            raise AppError("request_not_found", f"Agent request not found: {request_id}", ModuleName.BACKEND)
        return AgentRequestStateResponse(
            request_id=item.request_id,
            session_id=item.session_id,
            status=item.status.value,
            process_version=item.process_version,
            answer=item.answer,
            error=item.error,
            created_at=item.created_at,
            completed_at=item.completed_at,
        )
