from __future__ import annotations

from types import SimpleNamespace

from app.core.exceptions import AppError
from app.modules.agent.task_runtime.facade import AgentTaskRuntimeFacade
from app.modules.api.domain.models.agent_session import AgentSession
from app.modules.agent.orchestration.context.execution_context import ExecutionContext
from app.schemas.common import ModuleName


class TaskRuntimeAdapter:
    def __init__(self, runtime: AgentTaskRuntimeFacade) -> None:
        self._runtime = runtime

    async def run(self, context: ExecutionContext) -> SimpleNamespace:
        rag_session_id = context.session.active_rag_session_id
        if not rag_session_id:
            raise AppError(
                "rag_session_not_bound",
                "Agent session has no active rag_session_id for process v2.",
                ModuleName.RAG,
            )

        def progress_cb(stage: str, message: str, kind: str = "task_progress", meta: dict | None = None):
            payload = dict(meta or {})
            payload.setdefault("kind", kind)
            return context.publisher.publish_status(
                context.request.request_id,
                stage,
                message,
                payload,
            )

        return await self._runtime.run(
            task_id=context.request.request_id,
            dialog_session_id=context.session.session_id,
            rag_session_id=rag_session_id,
            mode="auto",
            message=context.request.message,
            attachments=[],
            files=[],
            progress_cb=progress_cb,
        )
