"""Spawn tool for creating background subagents."""

import secrets
from typing import Any, TYPE_CHECKING

from kyber.agent.tools.base import Tool

if TYPE_CHECKING:
    from kyber.agent.subagent import SubagentManager


def _make_receipt(prefix: str = "⚡") -> str:
    """Generate a short cryptographic receipt token.

    The agent must echo this token in its response to prove it actually
    called spawn rather than hallucinating the action.
    """
    return f"{prefix}{secrets.token_hex(4)}"


def make_start_receipt() -> str:
    """Generate a start receipt for when a subagent begins work."""
    return _make_receipt("⚡")


def make_completion_receipt() -> str:
    """Generate a completion receipt for when a subagent finishes work.

    This receipt is generated inside the subagent execution loop ONLY
    when the work is actually done. The main agent cannot claim task
    completion without presenting this token.
    """
    return _make_receipt("✅")


class SpawnTool(Tool):
    """
    Tool to spawn a subagent for background task execution.
    
    The subagent runs asynchronously and announces its result back
    to the main agent when complete.
    """
    
    def __init__(self, manager: "SubagentManager"):
        self._manager = manager
        self._origin_channel = "cli"
        self._origin_chat_id = "direct"
        # Receipts issued during the current request. The agent loop checks
        # that the final response contains at least one of these tokens when
        # the agent claims to have spawned work.
        self.pending_receipts: list[str] = []
    
    def set_context(self, channel: str, chat_id: str) -> None:
        """Set the origin context for subagent announcements."""
        self._origin_channel = channel
        self._origin_chat_id = chat_id
    
    @property
    def name(self) -> str:
        return "spawn"
    
    @property
    def description(self) -> str:
        return (
            "Spawn a subagent to handle a task in the background. "
            "Use this BEFORE doing any tool calls when a request will require multiple steps "
            "(file creation, code projects, system admin, research, installations, etc.). "
            "Your text response alongside this tool call will be sent to the user immediately "
            "as an acknowledgment, so include a brief natural message about what you're going to do. "
            "The subagent will complete the task and report back when done."
        )
    
    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "task": {
                    "type": "string",
                    "description": "The task for the subagent to complete",
                },
                "label": {
                    "type": "string",
                    "description": "Optional short label for the task (for display)",
                },
            },
            "required": ["task"],
        }
    
    async def execute(self, task: str, label: str | None = None, **kwargs: Any) -> str:
        """Spawn a subagent to execute the given task."""
        receipt = make_start_receipt()
        self.pending_receipts.append(receipt)

        result = await self._manager.spawn(
            task=task,
            label=label,
            origin_channel=self._origin_channel,
            origin_chat_id=self._origin_chat_id,
        )
        return (
            f"{result}\n\n"
            f"Task ref: {receipt}"
        )
