#!/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 create_plan, generate_task_id
from tools_library.cheapclaw_start_task.cheapclaw_start_task import CheapClawStartTaskTool
from tool_server_lite.tools.file_tools import BaseTool

class CheapClawSchedulePlanTool(BaseTool):
    name = "cheapclaw_schedule_plan"
    def execute(self, task_id, parameters):
        name = str(parameters.get("name") or "").strip()
        scope = str(parameters.get("scope") or "").strip()
        if not name or not scope:
            return {"status": "error", "output": "", "error": "name and scope are required"}
        resolved_task_id = str(parameters.get("task_id") or "").strip()
        started_task = None
        if scope == "task" and not resolved_task_id:
            channel = str(parameters.get("channel") or "").strip()
            conversation_id = str(parameters.get("conversation_id") or "").strip()
            task_name = str(parameters.get("task_name") or "").strip()
            user_input = str(parameters.get("user_input") or parameters.get("bootstrap_user_input") or "").strip()
            if not channel or not conversation_id or not task_name or not user_input:
                return {
                    "status": "error",
                    "output": "",
                    "error": "for scope=task without task_id, channel, conversation_id, task_name and bootstrap_user_input/user_input are required",
                }
            resolved_task_id = generate_task_id(channel, conversation_id, task_name)
            bootstrap_input = (
                "这是一个周期计划任务的初始化阶段。\n"
                "当前只做必要准备，例如创建脚本、缓存、配置、system-add.md 或说明文件。\n"
                "不要把这次初始化视为真正的周期执行，不要现在就向用户发送本计划应该定时发送的内容。\n"
                "真正执行时，系统后续会通过计划消息再次唤醒你。\n\n"
                f"{user_input}"
            )
            start_parameters = {
                "task_id": resolved_task_id,
                "channel": channel,
                "conversation_id": conversation_id,
                "task_name": task_name,
                "user_input": bootstrap_input,
                "agent_system": str(parameters.get("agent_system") or "").strip() or "CheapClawWorkerScheduled",
                "agent_name": str(parameters.get("agent_name") or "").strip() or "scheduled_worker",
                "display_name": str(parameters.get("display_name") or task_name).strip() or task_name,
                "source_message_ids": parameters.get("source_message_ids") or [],
            }
            optional_keys = [
                "conversation_type",
                "require_mention",
                "exposed_skills",
                "config",
                "force_new",
            ]
            for key in optional_keys:
                if key in parameters:
                    start_parameters[key] = parameters.get(key)
            started_task = CheapClawStartTaskTool().execute(task_id, start_parameters)
            if started_task.get("status") != "success":
                return started_task
        plan = create_plan(
            name=name,
            scope=scope,
            task_id=resolved_task_id,
            channel=str(parameters.get("channel") or "").strip(),
            conversation_id=str(parameters.get("conversation_id") or "").strip(),
            interval_sec=int(parameters.get("interval_sec") or 0),
            once_at=str(parameters.get("once_at") or "").strip(),
            schedule_type=str(parameters.get("schedule_type") or "").strip(),
            time_of_day=str(parameters.get("time_of_day") or "").strip(),
            days_of_week=parameters.get("days_of_week") or [],
            message=str(parameters.get("message") or "").strip(),
            enabled=bool(parameters.get("enabled", True)),
        )
        result = {"status": "success", "output": f"created plan {plan['plan_id']}", "plan": plan}
        if started_task is not None:
            result["started_task"] = started_task
            result["task_id"] = resolved_task_id
        return result
