from __future__ import annotations

from app.modules.agent.intent_router_v2 import ConversationState
from app.modules.agent.runtime.steps.retrieval import RuntimeRepoContextFactory

from app.modules.agent.task_runtime.models import TaskRuntimeContext


class TaskRuntimeContextBuilder:
    def __init__(self, repo_context_factory: RuntimeRepoContextFactory | None = None) -> None:
        self._repo_context_factory = repo_context_factory or RuntimeRepoContextFactory()

    def build(
        self,
        *,
        task_id: str,
        dialog_session_id: str,
        rag_session_id: str,
        mode: str,
        message: str,
        attachments: list[dict],
        files: list[dict],
        progress_cb,
        trace=None,
    ) -> TaskRuntimeContext:
        files_map = self._files_to_map(files)
        return TaskRuntimeContext(
            task_id=task_id,
            dialog_session_id=dialog_session_id,
            rag_session_id=rag_session_id,
            mode=mode,
            message=message,
            attachments=list(attachments or []),
            files=list(files or []),
            files_map=files_map,
            progress_cb=progress_cb,
            trace=trace,
            repo_context=self._repo_context_factory.build(files_map),
            conversation_state=ConversationState(),
        )

    def _files_to_map(self, files: list[dict]) -> dict[str, dict]:
        out: dict[str, dict] = {}
        for item in files or []:
            if isinstance(item, dict) and item.get("path"):
                out[str(item["path"])] = dict(item)
        return out
