#!/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 (
    bind_messages_to_task,
    create_plan,
    ensure_periodic_agent_overlay,
    generate_task_id,
    update_conversation_task,
    update_task_runtime_metadata,
)
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()
        requested_agent_system = str(parameters.get("agent_system") or "").strip() or "CheapClawWorkerGeneral"
        if requested_agent_system.endswith("_tmp"):
            return {
                "status": "error",
                "output": "",
                "error": "agent_system 不应直接传入隐藏的 _tmp 周期变体，请传入原始可见 agent_system",
            }
        requested_agent_name = str(parameters.get("agent_name") or "").strip()
        if not requested_agent_name and requested_agent_system == "CheapClawWorkerGeneral":
            requested_agent_name = "worker_agent"
        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()
        bootstrap_user_input = str(parameters.get("bootstrap_user_input") or parameters.get("user_input") or "").strip()
        source_message_ids = parameters.get("source_message_ids") or []

        if scope == "task" and not resolved_task_id:
            if not channel or not conversation_id or not task_name:
                return {
                    "status": "error",
                    "output": "",
                    "error": "for scope=task without task_id, channel, conversation_id and task_name are required",
                }
            resolved_task_id = generate_task_id(channel, conversation_id, task_name)
        elif scope == "task":
            if (channel and not conversation_id) or (conversation_id and not channel):
                return {
                    "status": "error",
                    "output": "",
                    "error": "for scope=task, channel and conversation_id must be provided together",
                }
        overlay_payload = None
        if scope == "task" and resolved_task_id:
            overlay_payload = ensure_periodic_agent_overlay(
                resolved_task_id,
                agent_system=requested_agent_system,
                agent_name=requested_agent_name,
            )
            if overlay_payload.get("status") != "success":
                return {
                    "status": "error",
                    "output": "",
                    "error": str(overlay_payload.get("error") or "failed to prepare periodic agent overlay"),
                    "overlay": overlay_payload,
                }
            runtime_agent_system = str(overlay_payload.get("periodic_agent_system") or "").strip() or requested_agent_system
        else:
            runtime_agent_system = requested_agent_system
        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(),
            agent_system=runtime_agent_system if scope == "task" else "",
            agent_name=requested_agent_name if scope == "task" else "",
            task_name=task_name if scope == "task" else "",
            display_name=str(parameters.get("display_name") or "").strip() if scope == "task" else "",
            bootstrap_user_input=bootstrap_user_input if scope == "task" else "",
            enabled=bool(parameters.get("enabled", True)),
        )
        if scope == "task" and resolved_task_id and channel and conversation_id:
            update_conversation_task(
                channel,
                conversation_id,
                resolved_task_id,
                {
                    "agent_system": requested_agent_system,
                    "agent_name": requested_agent_name,
                    "display_name": str(parameters.get("display_name") or task_name or Path(resolved_task_id).name).strip(),
                    "periodic_task": True,
                    "plan_managed": True,
                    "periodic_plan_id": str(plan.get("plan_id") or ""),
                    "periodic_plan_name": name,
                    "periodic_task_name": task_name or Path(resolved_task_id).name,
                    "periodic_agent_system": runtime_agent_system,
                    "periodic_agent_name": requested_agent_name,
                    "periodic_source_agent_system": requested_agent_system,
                    "periodic_channel": channel,
                    "periodic_conversation_id": conversation_id,
                    "periodic_bootstrap_user_input": bootstrap_user_input,
                },
            )
            if isinstance(source_message_ids, list) and source_message_ids:
                bind_messages_to_task(
                    channel,
                    conversation_id,
                    resolved_task_id,
                    source_message_ids,
                    note="periodic plan created from supervisor decision",
                )
            update_task_runtime_metadata(
                resolved_task_id,
                periodic_task=True,
                plan_managed=True,
                periodic_plan_id=str(plan.get("plan_id") or ""),
                periodic_plan_name=name,
                periodic_task_name=task_name or Path(resolved_task_id).name,
                periodic_agent_system=runtime_agent_system,
                periodic_agent_name=requested_agent_name,
                periodic_source_agent_system=requested_agent_system,
                periodic_channel=channel,
                periodic_conversation_id=conversation_id,
                periodic_bootstrap_user_input=bootstrap_user_input,
            )
        return {
            "status": "success",
            "output": f"created plan {plan['plan_id']}",
            "plan": plan,
            "task_id": resolved_task_id,
            "requested_agent_system": requested_agent_system,
            "requested_agent_name": requested_agent_name,
            "runtime_agent_system": runtime_agent_system,
        }
