#!/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 cancel_plan, cancel_plans
from tool_server_lite.tools.file_tools import BaseTool

class CheapClawCancelPlanTool(BaseTool):
    name = "cheapclaw_cancel_plan"
    def execute(self, task_id, parameters):
        plan_id = str(parameters.get("plan_id") or "").strip()
        if plan_id:
            ok = cancel_plan(plan_id)
            if not ok:
                return {"status": "error", "output": "", "error": f"plan not found: {plan_id}"}
            return {
                "status": "success",
                "output": f"cancelled {plan_id}",
                "matched_plan_ids": [plan_id],
                "cancelled_plan_ids": [plan_id],
                "matched_count": 1,
                "cancelled_count": 1,
            }
        result = cancel_plans(
            name=str(parameters.get("name") or "").strip(),
            task_id=str(parameters.get("task_id") or "").strip(),
            channel=str(parameters.get("channel") or "").strip(),
            conversation_id=str(parameters.get("conversation_id") or "").strip(),
            scope=str(parameters.get("scope") or "").strip(),
        )
        if result.get("status") != "success":
            return {"status": "error", "output": "", "error": str(result.get("error") or "plan not found")}
        matched_ids = result.get("matched_plan_ids") or []
        cancelled_ids = result.get("cancelled_plan_ids") or []
        return {
            "status": "success",
            "output": f"matched={len(matched_ids)} cancelled={len(cancelled_ids)}",
            **result,
        }
