from __future__ import annotations

import asyncio

from app.modules.api.domain.models.agent_request import AgentRequest
from app.modules.api.infrastructure.ids.request_id_factory import RequestIdFactory
from app.modules.api.infrastructure.stores.in_memory_request_store import InMemoryRequestStore
from app.modules.api.application.session_service import SessionService
from app.modules.agent.orchestration.facade import OrchestrationFacade


class RequestService:
    def __init__(
        self,
        request_store: InMemoryRequestStore,
        request_ids: RequestIdFactory,
        sessions: SessionService,
        orchestration: OrchestrationFacade,
    ) -> None:
        self._request_store = request_store
        self._request_ids = request_ids
        self._sessions = sessions
        self._orchestration = orchestration

    async def create(self, session_id: str, message: str, process_version: str) -> AgentRequest:
        session = self._sessions.get(session_id)
        request = AgentRequest.create(
            request_id=self._request_ids.create(),
            session_id=session_id,
            message=message,
            process_version=process_version,
        )
        self._request_store.save(request)
        asyncio.create_task(self._orchestration.run(request, session))
        return request

    def get(self, request_id: str) -> AgentRequest | None:
        return self._request_store.get(request_id)
