from __future__ import annotations

import asyncio
from types import SimpleNamespace

from app.modules.agent.intent_router_v2 import IntentRouterV2
from app.modules.agent.task_runtime.context import TaskRuntimeContextBuilder
from app.modules.agent.task_runtime.dispatcher import TaskWorkflowDispatcher
from app.modules.agent.task_runtime.enrichment import ContextEnrichmentService
from app.modules.agent.task_runtime.status_events import emit_status_block


class AgentTaskRuntimeFacade:
    def __init__(
        self,
        *,
        router: IntentRouterV2,
        context_builder: TaskRuntimeContextBuilder,
        enrichment: ContextEnrichmentService,
        dispatcher: TaskWorkflowDispatcher,
    ) -> None:
        self._router = router
        self._context_builder = context_builder
        self._enrichment = enrichment
        self._dispatcher = dispatcher

    async def run(
        self,
        *,
        task_id: str,
        dialog_session_id: str,
        rag_session_id: str,
        mode: str,
        message: str,
        attachments: list[dict],
        files: list[dict],
        progress_cb=None,
    ):
        ctx = self._context_builder.build(
            task_id=task_id,
            dialog_session_id=dialog_session_id,
            rag_session_id=rag_session_id,
            mode=mode,
            message=message,
            attachments=attachments,
            files=files,
            progress_cb=progress_cb,
        )
        self._notify(progress_cb, "runtime.router", "Маршрутизирую запрос по task workflows.", {"mode": mode})
        ctx.route_result = self._router.route(message, ctx.conversation_state, ctx.repo_context)
        emit_status_block(
            ctx,
            block_id="intent_router",
            title="Intent Router",
            lines=[
                f"intent: {ctx.route_result.intent}",
                f"sub_intent: {ctx.route_result.query_plan.sub_intent}",
                f"conversation_mode: {ctx.route_result.conversation_mode}",
                f"matched_source: {ctx.route_result.matched_intent_source}",
            ],
        )
        self._notify(progress_cb, "runtime.context", "Собираю контекст для выбранного workflow.", {"intent": ctx.route_result.intent})
        ctx.enriched_context = self._enrichment.enrich(ctx)
        loop = asyncio.get_running_loop()
        self._notify(progress_cb, "runtime.workflow", "Запускаю целевой task workflow.", {"intent": ctx.route_result.intent})
        emit_status_block(
            ctx,
            block_id="workflow",
            title="Task Workflow",
            lines=[
                f"intent: {ctx.route_result.intent}",
                f"sub_intent: {ctx.route_result.query_plan.sub_intent}",
                "dispatcher: task_workflow_dispatcher",
            ],
        )
        result = await loop.run_in_executor(None, lambda: self._dispatcher.dispatch(ctx))
        return SimpleNamespace(
            result_type=result.result_type,
            answer=result.answer,
            artifacts=result.artifacts,
            changeset=[],
            meta={
                "task_id": task_id,
                "intent": ctx.route_result.intent,
                "workflow_meta": result.meta,
                "route": ctx.route_result.model_dump(mode="json"),
            },
        )

    def _notify(self, progress_cb, stage: str, message: str, meta: dict) -> None:
        if progress_cb is not None:
            progress_cb(stage, message, "task_progress", meta)
