"""Sub-agent delegation via the `task` tool.

Spawns an isolated ClawAgent.invoke() with a fresh context window.
Only the final result is returned to the parent agent.
"""

import asyncio
from typing import Any, Dict, List, Optional

from clawagents.providers.llm import LLMProvider
from clawagents.tools.registry import Tool, ToolRegistry, ToolResult


class TaskTool:
    name = "task"
    description = (
        "Delegate a task to a sub-agent with its own isolated context window. "
        "Use for complex sub-tasks that would clutter your main context. "
        "The sub-agent has access to the same tools but a fresh conversation."
    )
    parameters = {
        "description": {
            "type": "string",
            "description": "What the sub-agent should accomplish",
            "required": True,
        },
        "max_iterations": {
            "type": "number",
            "description": "Max tool rounds for the sub-agent. Default: 5",
        },
    }

    def __init__(self, llm: LLMProvider, tools: ToolRegistry):
        self._llm = llm
        self._tools = tools

    async def execute(self, args: Dict[str, Any]) -> ToolResult:
        from clawagents.graph.agent_loop import run_agent_graph

        description = str(args.get("description", ""))
        max_iter = int(args.get("max_iterations", 5))

        if not description:
            return ToolResult(success=False, output="", error="No task description provided")

        try:
            state = await run_agent_graph(
                task=description,
                llm=self._llm,
                tools=self._tools,
                max_iterations=max_iter,
                streaming=False,
                # No hooks in sub-agents by default (clean context)
            )

            if state.status == "error":
                return ToolResult(
                    success=False,
                    output=state.result or "",
                    error=f"Sub-agent failed: {state.result}",
                )

            return ToolResult(
                success=True,
                output=f"[Sub-agent completed: {state.tool_calls} tool calls, {state.iterations} iterations]\n\n{state.result}",
            )
        except Exception as e:
            return ToolResult(success=False, output="", error=f"Sub-agent error: {str(e)}")


def create_task_tool(llm: LLMProvider, tools: ToolRegistry) -> Tool:
    """Factory function to create a TaskTool with the parent's LLM and tools."""
    return TaskTool(llm=llm, tools=tools)
