from __future__ import annotations

try:
    from langgraph.graph import END, START, StateGraph
except ImportError:  # pragma: no cover - exercised only in offline sandbox
    from .langgraph_compat import END, START, StateGraph

from .nodes import (
    PipelineState,
    gap_analysis_node,
    gather_node,
    research_node,
    should_research,
    synthesise_node,
    write_node,
)


def build_graph():
    graph = StateGraph(PipelineState)
    graph.add_node("gather", gather_node)
    graph.add_node("gap_analysis", gap_analysis_node)
    graph.add_node("research", research_node)
    graph.add_node("synthesise", synthesise_node)
    graph.add_node("write", write_node)

    graph.add_edge(START, "gather")
    graph.add_edge("gather", "gap_analysis")
    graph.add_conditional_edges(
        "gap_analysis",
        should_research,
        {
            "research": "research",
            "skip_research": "synthesise",
        },
    )
    graph.add_edge("research", "synthesise")
    graph.add_edge("synthesise", "write")
    graph.add_edge("write", END)
    return graph.compile()
