from langgraph.graph import StateGraph, START, END

from .agents import sentiment_agent, issue_agent, risk_agent, routing_agent
from .aggregator import aggregate_results
from .state import FeedbackState


def build_graph():
    builder = StateGraph(FeedbackState)

    builder.add_node("sentiment_agent", sentiment_agent)
    builder.add_node("issue_agent", issue_agent)
    builder.add_node("risk_agent", risk_agent)
    builder.add_node("routing_agent", routing_agent)
    builder.add_node("fan_in_aggregator", aggregate_results)

    # FAN-OUT: the same feedback is sent to four workers in parallel.
    builder.add_edge(START, "sentiment_agent")
    builder.add_edge(START, "issue_agent")
    builder.add_edge(START, "risk_agent")
    builder.add_edge(START, "routing_agent")

    # FAN-IN: aggregator waits for all four upstream branches.
    builder.add_edge("sentiment_agent", "fan_in_aggregator")
    builder.add_edge("issue_agent", "fan_in_aggregator")
    builder.add_edge("risk_agent", "fan_in_aggregator")
    builder.add_edge("routing_agent", "fan_in_aggregator")

    builder.add_edge("fan_in_aggregator", END)

    return builder.compile()


feedback_graph = build_graph()
