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

import argparse
import json
import sys
from pathlib import Path

from common import dump_json, find_agent_entry, load_openclaw_config, ensure_agent_entry


def list_config(agent_id: str, config_path: Path | None = None) -> dict:
    config = load_openclaw_config(config_path)
    entry = ensure_agent_entry(config, agent_id)

    skills = entry.get("skills", [])
    if not isinstance(skills, list):
        skills = []

    tools = entry.get("tools", {})
    if not isinstance(tools, dict):
        tools = {}
    tools_deny = tools.get("deny", [])
    if not isinstance(tools_deny, list):
        tools_deny = []

    return {
        "agent_id": agent_id,
        "skills": skills,
        "tools_deny": tools_deny,
        "model": entry.get("model"),
        "workspace": entry.get("workspace"),
        "identity": entry.get("identity"),
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="列出 Agent 当前的 skills 和 tools 状态")
    parser.add_argument("--agent-id", required=True, help="Agent ID")
    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 = list_config(args.agent_id, config_path)
        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,
        }
        json.dump(error, sys.stdout, indent=2, ensure_ascii=False)
        sys.stdout.write("\n")
        return 1


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