from __future__ import annotations

import logging

from langgraph.graph import END, START, StateGraph

from app.modules.agent.code_qa_runtime import CodeQaRuntimeExecutor
from app.modules.agent.engine.graphs.progress import emit_progress_sync
from app.modules.agent.engine.graphs.state import AgentGraphState
from app.modules.agent.llm import AgentLlmService

LOGGER = logging.getLogger(__name__)


class CodeQaGraphFactory:
    def __init__(self, llm: AgentLlmService) -> None:
        self._executor = CodeQaRuntimeExecutor(llm)

    def build(self, checkpointer=None):
        graph = StateGraph(AgentGraphState)
        graph.add_node("execute_code_qa", self._execute_code_qa)
        graph.add_edge(START, "execute_code_qa")
        graph.add_edge("execute_code_qa", END)
        return graph.compile(checkpointer=checkpointer)

    def _execute_code_qa(self, state: AgentGraphState) -> dict:
        emit_progress_sync(
            state,
            stage="graph.project_qa.code_qa",
            message="Исполняю CODE_QA runtime pipeline.",
        )
        result = self._executor.execute(
            user_query=str(state.get("message", "") or ""),
            rag_session_id=str(state.get("project_id", "") or ""),
            files_map=dict(state.get("files_map", {}) or {}),
        )
        LOGGER.warning(
            "graph step result: graph=project_qa/code_qa_runtime answer_mode=%s repair_used=%s",
            result.answer_mode,
            result.repair_used,
        )
        return {
            "final_answer": result.final_answer,
            "code_qa_result": result.model_dump(mode="json"),
        }
