"""Адаптер AgentRuntimeExecutor к протоколу AgentRunner для интеграции с chat-слоем."""

from __future__ import annotations

import asyncio
import logging

from app.modules.agent.runtime import AgentRuntimeExecutor
from app.modules.contracts import AgentRunner
from app.schemas.chat import TaskResultType

LOGGER = logging.getLogger(__name__)


class CodeQaRunnerAdapter:
    """Реализация AgentRunner через AgentRuntimeExecutor (sync execute в executor)."""

    def __init__(self, executor: AgentRuntimeExecutor) -> None:
        self._executor = executor

    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,
    ):
        files_map = _files_to_map(files)
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(
            None,
            lambda: self._executor.execute(
                user_query=message,
                rag_session_id=rag_session_id,
                files_map=files_map,
            ),
        )
        return _to_agent_run_result(result, task_id=task_id)


def _files_to_map(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


def _to_agent_run_result(final, *, task_id: str):
    from types import SimpleNamespace

    meta = {}
    if final:
        meta = {
            "task_id": task_id,
            "answer_mode": getattr(final, "answer_mode", "normal"),
        }
        if getattr(final, "diagnostics", None) is not None:
            meta["diagnostics"] = getattr(final.diagnostics, "model_dump", lambda **kw: {})(mode="json")
    return SimpleNamespace(
        result_type=TaskResultType.ANSWER,
        answer=final.final_answer if final else "",
        changeset=[],
        meta=meta,
    )
