#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from common import (
    backup_config,
    dump_json,
    load_openclaw_config,
    ensure_agent_entry,
    make_result,
    validate_json,
)


def toggle_skill(
    agent_id: str,
    skill_name: str,
    action: str,
    config_path: Path | None = None,
    dry_run: bool = False,
) -> dict:
    resolved_path = config_path or Path("~/.openclaw/openclaw.json").expanduser().resolve()
    config = load_openclaw_config(resolved_path)
    entry = ensure_agent_entry(config, agent_id)
    skills: list[str] = list(entry.get("skills", []) or [])

    if action == "enable":
        if skill_name in skills:
            return make_result(
                "enable_skill",
                agent_id,
                "skills",
                before=skills,
                after=skills,
                changed=False,
                message=f"skill '{skill_name}' 已经处于启用状态，无需操作",
            )
        new_skills = skills + [skill_name]
        result = make_result(
            "enable_skill",
            agent_id,
            "skills",
            before=skills,
            after=new_skills,
            changed=True,
            dry_run=dry_run,
            message=f"将启用 skill: {skill_name}",
        )
    elif action == "disable":
        if skill_name not in skills:
            return make_result(
                "disable_skill",
                agent_id,
                "skills",
                before=skills,
                after=skills,
                changed=False,
                message=f"skill '{skill_name}' 已经处于禁用状态，无需操作",
            )
        new_skills = [s for s in skills if s != skill_name]
        result = make_result(
            "disable_skill",
            agent_id,
            "skills",
            before=skills,
            after=new_skills,
            changed=True,
            dry_run=dry_run,
            message=f"将禁用 skill: {skill_name}",
        )
    else:
        raise ValueError(f"无效的 action: {action}，请使用 enable 或 disable")

    if dry_run or not result["changed"]:
        return result

    entry["skills"] = new_skills
    if not validate_json(config):
        entry["skills"] = skills
        raise ValueError("配置 JSON 校验失败，变更已回滚，openclaw.json 未被修改")

    backup_path = backup_config(resolved_path)
    dump_json(resolved_path, config)
    result["backup"] = str(backup_path)
    return result


def main() -> int:
    parser = argparse.ArgumentParser(description="启用或禁用 Agent 的某个 skill")
    parser.add_argument("--agent-id", required=True, help="Agent ID")
    parser.add_argument("--skill-name", required=True, help="skill 名称")
    parser.add_argument(
        "--action", required=True, choices=["enable", "disable"], help="enable=启用, disable=禁用"
    )
    parser.add_argument("--dry-run", action="store_true", help="仅预览变更，不实际写入")
    parser.add_argument(
        "--config",
        help="openclaw.json 路径（默认 ~/.openclaw/openclaw.json）",
    )
    args = parser.parse_args()

    try:
        config_path = Path(args.config).expanduser().resolve() if args.config else None
        result = toggle_skill(args.agent_id, args.skill_name, args.action, config_path, args.dry_run)
        json.dump(result, sys.stdout, indent=2, ensure_ascii=False)
        sys.stdout.write("\n")
        return 0
    except (FileNotFoundError, ValueError) as e:
        error = {
            "error": str(e),
            "agent_id": args.agent_id,
            "skill_name": args.skill_name,
            "action": args.action,
        }
        json.dump(error, sys.stdout, indent=2, ensure_ascii=False)
        sys.stdout.write("\n")
        return 1


if __name__ == "__main__":
    raise SystemExit(main())