"""sessions_list tool — list background tasks from the subagent registry."""

from typing import Any, TYPE_CHECKING

from flowly.agent.tools.base import Tool

if TYPE_CHECKING:
    from flowly.agent.subagent_registry import SubagentRegistry


class SessionsListTool(Tool):
    """List background tasks (running and recently completed)."""

    def __init__(self, registry: "SubagentRegistry"):
        self._registry = registry

    @property
    def name(self) -> str:
        return "sessions_list"

    @property
    def description(self) -> str:
        return (
            "List background tasks that have been spawned. "
            "Shows running, completed, and failed tasks. "
            "Use this to check the status of background work."
        )

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "enum": ["running", "completed", "failed", "all"],
                    "description": "Filter by status. Defaults to 'all'.",
                },
            },
            "required": [],
        }

    async def execute(self, status: str = "all", **kwargs: Any) -> str:
        runs = self._registry.all()

        if not runs:
            return "No background tasks found."

        # Filter
        filtered = []
        for r in runs:
            if status == "running" and r.ended_at is not None:
                continue
            if status == "completed" and r.outcome != "ok":
                continue
            if status == "failed" and r.outcome not in ("error", "timeout"):
                continue
            filtered.append(r)

        if not filtered:
            return f"No tasks with status '{status}'."

        lines = [f"Background tasks ({len(filtered)}):"]
        for r in sorted(filtered, key=lambda x: x.created_at, reverse=True):
            if r.ended_at is None:
                state = "⏳ running"
            elif r.outcome == "ok":
                state = "✓ completed"
            elif r.outcome == "timeout":
                state = "⏰ timed out"
            else:
                state = "✗ failed"

            duration = ""
            if r.started_at and r.ended_at:
                secs = int(r.ended_at - r.started_at)
                duration = f" ({secs}s)"

            lines.append(f"  {state}{duration} — {r.label} [{r.run_id[:8]}]")
            if r.error:
                lines.append(f"    error: {r.error}")

        return "\n".join(lines)
