import logging

from langgraph.graph import END, START, StateGraph

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 ProjectQaGraphFactory:
    def __init__(self, llm: AgentLlmService) -> None:
        self._llm = llm

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

    def _answer_node(self, state: AgentGraphState) -> dict:
        emit_progress_sync(
            state,
            stage="graph.project_qa.answer",
            message="Готовлю ответ по контексту текущего проекта.",
        )
        user_input = "\n\n".join(
            [
                f"User request:\n{state.get('message', '')}",
                f"RAG context:\n{state.get('rag_context', '')}",
                f"Confluence context:\n{state.get('confluence_context', '')}",
            ]
        )
        answer = self._llm.generate("project_answer", user_input, log_context="graph.project_qa.answer")
        emit_progress_sync(
            state,
            stage="graph.project_qa.answer.done",
            message="Ответ по проекту сформирован.",
        )
        result = {"answer": answer}
        LOGGER.warning(
            "graph step result: graph=project_qa step=answer answer_len=%s",
            len(answer or ""),
        )
        return result
