"""Graph definition generated from blueprint: {{ ir.name }}"""
# Generated by agent-blueprint {{ ir.version }}

import os

from langgraph.graph import StateGraph, END
{% if ir.memory.backend.value == "in_memory" %}
from langgraph.checkpoint.memory import MemorySaver
{% elif ir.memory.backend.value == "sqlite" %}
from langgraph.checkpoint.sqlite import SqliteSaver
{% elif ir.memory.backend.value == "postgres" %}
from langgraph.checkpoint.postgres import PostgresSaver
{% elif ir.memory.backend.value == "redis" %}
from langgraph.checkpoint.redis import RedisSaver
{% endif %}

from state import AgentState
from nodes import (
{% for node in ir.nodes %}
    node_{{ node.id | safe_id }},
{% endfor %}
)


def build_graph():
    builder = StateGraph(AgentState)

    # Register nodes
{% for node in ir.nodes %}
    builder.add_node("{{ node.id }}", node_{{ node.id | safe_id }})
{% endfor %}

    # Set entry point
    builder.set_entry_point("{{ ir.entry_point }}")

    # Add edges
{% for edge in ir.edges %}
{% if edge.is_conditional %}
    def _route_{{ edge.from_node | safe_id }}(state: AgentState) -> str:
{% for target in edge.targets %}
{% if target.condition %}
        if {{ target.condition.to_dict_access('state') }}:
            return "{{ target.target }}"
{% endif %}
{% endfor %}
{% for target in edge.targets %}
{% if target.is_default and not target.condition %}
        return "{{ target.target }}"
{% endif %}
{% endfor %}

    builder.add_conditional_edges(
        "{{ edge.from_node }}",
        _route_{{ edge.from_node | safe_id }},
        {
{% for target in edge.targets %}
            "{{ target.target }}": {% if target.target == "END" %}END{% else %}"{{ target.target }}"{% endif %},
{% endfor %}
        }
    )
{% else %}
{% for target in edge.targets %}
    builder.add_edge("{{ edge.from_node }}", {% if target.target == "END" %}END{% else %}"{{ target.target }}"{% endif %})
{% endfor %}
{% endif %}
{% endfor %}

    # Memory / checkpointing
{% if ir.memory.backend.value == "in_memory" %}
    checkpointer = MemorySaver()
{% elif ir.memory.backend.value == "sqlite" %}
    _db_path = os.environ.get("{{ ir.memory.connection_string_env or 'SQLITE_DB_PATH' }}", "{{ ir.name }}.db")
    checkpointer = SqliteSaver.from_conn_string(_db_path)
{% elif ir.memory.backend.value == "postgres" %}
    _pg_url = os.environ.get("{{ ir.memory.connection_string_env or 'DATABASE_URL' }}")
    if not _pg_url:
        raise RuntimeError(
            "Postgres checkpointer requires the '{{ ir.memory.connection_string_env or 'DATABASE_URL' }}' "
            "environment variable to be set."
        )
    checkpointer = PostgresSaver.from_conn_string(_pg_url)
{% elif ir.memory.backend.value == "redis" %}
    _redis_url = os.environ.get("{{ ir.memory.connection_string_env or 'REDIS_URL' }}", "redis://localhost:6379")
    checkpointer = RedisSaver.from_conn_string(_redis_url)
{% endif %}

    return builder.compile(checkpointer=checkpointer)


graph = build_graph()
