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

from crewai import Agent, Task, Crew
{% for imp in imports %}
{{ imp }}
{% endfor %}

# Create agents
{% for node in agent_nodes %}
{{ node.var_name }} = Agent(
    role={{ node.kwargs.get('role', "'Agent'") }},
    goal="Execute assigned workflow steps",
    backstory={{ node.kwargs.get('backstory', "'Generated from choreo-mini workflow conversion'") }},
    allow_delegation=False,
    verbose=True
)
{% endfor %}

AGENTS = [
{% for node in agent_nodes %}
    {{ node.var_name }},
{% endfor %}
]

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

CALL_STEPS = [
{% for call in send_calls %}
    {
        "kind": "send",
        "agent_expr": {{ call.agent_expr_literal }},
        "message_expr": {{ call.message_expr_literal }},
    },
{% endfor %}
{% for call in execute_calls %}
    {
        "kind": "execute",
        "agent_expr": {{ call.node_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 _task_description(step: dict, index: int) -> str:
    if step["kind"] == "send":
        return f"Workflow send step {index}: {step['message_expr']}"
    return f"Workflow execute step {index}: {step['message_expr']}"


def _build_tasks() -> list[Task]:
    tasks: list[Task] = []
    for index, step in enumerate(CALL_STEPS, start=1):
        agent = _resolve_agent(step["agent_expr"])
        if agent is None:
            if AGENTS:
                agent = AGENTS[0]
            else:
                continue

        tasks.append(
            Task(
                description=_task_description(step, index),
                agent=agent,
                expected_output="A helpful intermediate result",
            )
        )

    return tasks


tasks = _build_tasks()

# Create and run crew
crew = Crew(
    agents=AGENTS,
    tasks=tasks,
    verbose=True
)

if __name__ == "__main__":
    if not AGENTS:
        print("No AgentNode declarations found for CrewAI conversion.")
    elif not tasks:
        print("No executable call steps were found; generated crew has no tasks.")
    else:
        result = crew.kickoff()
        print("Crew result:", result)

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