"""Execute an agent turn — the core orchestration primitive.

Requires an AgentRepository to be wired into the service container.
Consumer repos configure this when building their transport layer.
"""

from core.pathways.context import Context
from core.pathways.models.tool import ToolOutput


async def run(
    agent_id: str,
    message: str,
    thread_id: str | None = None,
    pathway: str | None = None,
    context: Context | None = None,
) -> ToolOutput:
    """Execute a single turn with a registered agent.

    Args:
        agent_id: ID of the agent to execute (e.g., "researcher")
        message: The message/goal to send to the agent
        thread_id: Optional thread ID for conversation continuity
        pathway: Optional pathway override (user-defined pathway ID)
        context: Execution context (injected by framework)
    """
    if not agent_id:
        return ToolOutput(success=False, error="agent_id is required")
    if not message:
        return ToolOutput(success=False, error="message is required")

    if not context:
        return ToolOutput(success=False, error="Context not available")

    agent_repo = getattr(context.services, "agent_repo", None)
    if not agent_repo:
        return ToolOutput(
            success=False,
            error="AgentRepository not configured in ServiceContainer",
        )

    effective_thread_id = thread_id or context.run.thread_id or "tool_turn"

    try:
        agent = await agent_repo.get(agent_id)
        if not agent:
            return ToolOutput(success=False, error=f"Agent not found: {agent_id}")

        pathway_service = context.services.pathway_service
        pathway_executor = context.services.pathway_executor
        if not pathway_service or not pathway_executor:
            return ToolOutput(
                success=False,
                error="PathwayService or PathwayVM not configured",
            )

        result = await agent.turn(
            message=message,
            thread_id=effective_thread_id,
            pathway_vm=pathway_executor,
            pathway_service=pathway_service,
            pathway_override=pathway,
        )

        return ToolOutput(
            success=result.success,
            data={
                "agent_id": agent_id,
                "response": result.response,
                "steps_taken": result.steps_taken,
                "tokens_used": result.tokens_used,
            },
        )

    except Exception as e:
        return ToolOutput(
            success=False,
            error=f"Agent turn failed for '{agent_id}': {e}",
        )
