#!/usr/bin/env python3
from pathlib import Path
import sys

APP_ROOT = Path(__file__).resolve().parents[2]
if str(APP_ROOT) not in sys.path:
    sys.path.insert(0, str(APP_ROOT))

from tool_runtime_helpers import list_plans
from tool_server_lite.tools.file_tools import BaseTool


class CheapClawListPlansTool(BaseTool):
    name = "cheapclaw_list_plans"

    def execute(self, task_id, parameters):
        scope = str(parameters.get("scope") or "").strip()
        enabled_only = bool(parameters.get("enabled_only", False))
        name = str(parameters.get("name") or "").strip()
        task_id_filter = str(parameters.get("task_id") or "").strip()
        channel = str(parameters.get("channel") or "").strip()
        conversation_id = str(parameters.get("conversation_id") or "").strip()

        items = list_plans(scope=scope, enabled_only=enabled_only)
        filtered = []
        for item in items:
            if not isinstance(item, dict):
                continue
            if name and str(item.get("name") or "").strip() != name:
                continue
            if task_id_filter and str(item.get("task_id") or "").strip() != task_id_filter:
                continue
            if channel and str(item.get("channel") or "").strip() != channel:
                continue
            if conversation_id and str(item.get("conversation_id") or "").strip() != conversation_id:
                continue
            filtered.append(item)

        return {
            "status": "success",
            "output": f"plans={len(filtered)}",
            "plans": filtered,
            "plan_count": len(filtered),
        }
