# -*- coding: utf-8 -*-
"""CL CronTaskService 命令族（Phase 8 Tier 2 CL）

借鉴 zhikuncode CronTaskService：
- /cron list — 列出所有定时任务
- /cron create <interval_seconds> <command> — 创建定时任务
- /cron delete <id> — 删除指定任务
- /cron cleanup — 清理过期任务
- /cron clear — 清空所有任务

集成点：main.py handle_slash_command 注册 /cron 命令族。
CronTaskService 实例由 main.py 启动时创建并注入。
"""
from typing import Dict, List

from ..tools.cron_service import CronTaskService, DurableCronTask


def _format_task(task: DurableCronTask, now: float) -> str:
    """格式化单条任务为可读字符串。"""
    import time as _time

    def _fmt_ts(ts: float) -> str:
        if not ts:
            return "从未"
        return _time.strftime("%Y-%m-%d %H:%M:%S", _time.localtime(ts))

    next_in = max(0, int(task.next_run - now))
    interval = int(task.interval_seconds)

    # 间隔格式化
    if interval >= 86400:
        interval_str = f"{interval // 86400}天"
    elif interval >= 3600:
        interval_str = f"{interval // 3600}小时{max(0, (interval % 3600) // 60)}分"
    elif interval >= 60:
        interval_str = f"{interval // 60}分钟"
    else:
        interval_str = f"{interval}秒"

    return (
        f"  [{task.id[:8]}] 间隔={interval_str}  下次={_fmt_ts(task.next_run)}\n"
        f"    命令: {task.command}\n"
        f"    上次执行: {_fmt_ts(task.last_run or 0)}"
    )


def handle_cron(args: str, service: CronTaskService) -> str:
    """/cron 命令处理：管理定时任务。

    Args:
        args: 子命令及参数（如 "list" / "create 60 /build" / "delete abc123"）
        service: CronTaskService 实例

    Returns:
        可读的命令处理结果字符串
    """
    parts = args.split(maxsplit=1) if args else []
    if not parts:
        return _usage()

    sub = parts[0].lower()
    rest = parts[1] if len(parts) > 1 else ""

    if sub == "list":
        return _handle_list(service)
    if sub == "create":
        return _handle_create(rest, service)
    if sub == "delete":
        return _handle_delete(rest, service)
    if sub == "cleanup":
        return _handle_cleanup(service)
    if sub == "clear":
        return _handle_clear(service)

    return f"未知子命令: {sub}\n\n" + _usage()


def _usage() -> str:
    return (
        "用法:\n"
        "  /cron list                    列出所有定时任务\n"
        "  /cron create <秒> <命令>      创建定时任务（如 /cron create 60 /build）\n"
        "  /cron delete <id>             删除指定任务（id 取 list 输出的前 8 位）\n"
        "  /cron cleanup                 清理 30 天前创建的过期任务\n"
        "  /cron clear                   清空所有任务（不可恢复）"
    )


def _handle_list(service: CronTaskService) -> str:
    import time as _time

    tasks = service.list()
    if not tasks:
        return "（暂无定时任务）\n\n" + _usage()

    now = _time.time()
    lines = [f"📋 共 {len(tasks)} 条定时任务：", ""]
    for t in tasks:
        lines.append(_format_task(t, now))
    return "\n".join(lines)


def _handle_create(rest: str, service: CronTaskService) -> str:
    if not rest:
        return "用法: /cron create <间隔秒数> <命令>\n示例: /cron create 60 /build"

    parts = rest.split(maxsplit=1)
    if len(parts) < 2:
        return "用法: /cron create <间隔秒数> <命令>\n示例: /cron create 60 /build"

    try:
        interval = int(parts[0])
    except ValueError:
        return f"间隔秒数必须是整数，收到: {parts[0]}"

    if interval <= 0:
        return "间隔秒数必须 > 0"

    command = parts[1].strip()
    if not command:
        return "命令不能为空"

    task_id = service.create(interval=interval, command=command)
    return f"✓ 已创建定时任务\n  id: {task_id[:8]}\n  间隔: {interval} 秒\n  命令: {command}"


def _handle_delete(rest: str, service: CronTaskService) -> str:
    if not rest:
        return "用法: /cron delete <id>（id 取 list 输出的前 8 位）"

    target = rest.strip()
    # 支持 8 位短 id 匹配
    tasks = service.list()
    matched = [t for t in tasks if t.id.startswith(target)]
    if not matched:
        return f"未找到 id 以 {target} 开头的任务"
    if len(matched) > 1:
        return f"多个任务匹配 {target}，请提供更长的前缀"

    if service.delete(matched[0].id):
        return f"✓ 已删除任务 {matched[0].id[:8]}"
    return f"删除失败：任务 {matched[0].id[:8]} 不存在"


def _handle_cleanup(service: CronTaskService) -> str:
    purged = service.cleanup()
    remaining = service.count()
    return f"✓ 清理了 {purged} 条过期任务，剩余 {remaining} 条"


def _handle_clear(service: CronTaskService) -> str:
    tasks = service.list()
    for t in tasks:
        service.delete(t.id)
    return f"✓ 已清空所有 {len(tasks)} 条任务"


# /cron 命令注册元数据（供 main.py 使用）
CRON_COMMANDS = {
    "cron": "管理定时任务（list/create/delete/cleanup/clear）",
}
