"""Generated AutoGen workflow from choreo-mini code."""

from autogen import AssistantAgent, UserProxyAgent
{% for imp in imports %}
{{ imp }}
{% endfor %}

# Create agents
{% for node in agent_nodes %}
{{ node.var_name }} = AssistantAgent(
    name="{{ node.var_name }}",
    system_message={{ node.kwargs.get('system_prompt', node.kwargs.get('role', "'You are a helpful assistant.'")) }},
    llm_config={"config_list": [{"model": "gpt-4", "api_key": "your-key"}]}
)
{% endfor %}

AGENT_REGISTRY = {
{% for node in agent_nodes %}
    str({{ node.runtime_name_expr }}): {{ node.var_name }},
    "{{ node.var_name }}": {{ node.var_name }},
{% endfor %}
}

SEND_CALLS = [
{% for call in send_calls %}
    {
        "agent_expr": {{ call.agent_expr_literal }},
        "message_expr": {{ call.message_expr_literal }},
    },
{% endfor %}
]


def _resolve_agent(agent_expr: str):
    key = str(agent_expr).strip().strip("\"'")
    return AGENT_REGISTRY.get(key) or AGENT_REGISTRY.get(key.lower())


def _render_message(message_expr: str) -> str:
    return f"Generated from expression: {message_expr}"

# Create user proxy
user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=10,
    is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
    code_execution_config=False,
)

if __name__ == "__main__":
    if not AGENT_REGISTRY:
        print("No AgentNode declarations found for AutoGen conversion.")
    elif not SEND_CALLS:
        print("No wf.send calls were detected in execution logic.")
    else:
        for index, call in enumerate(SEND_CALLS, start=1):
            recipient = _resolve_agent(call["agent_expr"])
            if recipient is None:
                print(f"Skipping step {index}: unresolved agent expression {call['agent_expr']!r}")
                continue

            try:
                response = user_proxy.initiate_chat(
                    recipient,
                    message=_render_message(call["message_expr"]),
                )
                print(f"Step {index} response:", response)
            except Exception as exc:
                print(f"Step {index} failed: {exc}")

    {% if enable_profiling %}
    # Profiling data would be collected here
    print("Profiling enabled but not implemented in AutoGen template")
    {% endif %}
