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

import argparse
import json
import sys
from pathlib import Path

from common import (
    build_agent_entry,
    default_openclaw_config_path,
    load_agent_definition,
    load_openclaw_config,
    merge_placeholder_catalog_with_detected,
    normalize_placeholder_catalog,
    read_agent_placeholders,
    resolve_agent_directory,
    resolve_existing_agent_entry,
)


def resolve_install_params(agent_id: str, source_path: Path, config_path: Path) -> dict[str, object]:
    agent_def = load_agent_definition(agent_id, source_path)
    agent_dir = resolve_agent_directory(agent_id, source_path)
    entry = build_agent_entry(agent_def)
    identity = entry.get("identity", {})
    placeholders = read_agent_placeholders(agent_id, source_path)
    placeholder_catalog = normalize_placeholder_catalog(agent_def.get("placeholder_catalog"))
    placeholders_detail = merge_placeholder_catalog_with_detected(placeholder_catalog, placeholders)
    current_openclaw_id = None
    installed = False

    try:
        openclaw = load_openclaw_config(config_path)
    except FileNotFoundError:
        openclaw = None

    if openclaw is not None:
        existing_entry = resolve_existing_agent_entry(config_path, openclaw, agent_id, entry["workspace"])
        if existing_entry is not None:
            current_openclaw_id = existing_entry.get("id")
            installed = True

    return {
        "ok": True,
        "agent_id": agent_id,
        "source_path": str(source_path),
        "config_path": str(config_path),
        "agent_directory": str(agent_dir),
        "openclaw_id": current_openclaw_id or agent_id,
        "current_openclaw_id": current_openclaw_id,
        "installed": installed,
        "workspace": entry["workspace"],
        "agent_name": entry.get("name") or (identity.get("name") if isinstance(identity, dict) else None),
        "identity_name": identity.get("name") if isinstance(identity, dict) else None,
        "placeholders": placeholders,
        "placeholder_catalog": placeholder_catalog,
        "placeholders_detail": placeholders_detail,
        "needs_name_confirmation": bool(placeholders),
        "message": "已解析 Agent 的默认安装参数。",
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="解析 Agent 安装参数")
    parser.add_argument("--agent-id", required=True, help="Agent ID")
    parser.add_argument(
        "--path",
        required=True,
        help="Agent 下载目录（sophhub agent download 的 --path）",
    )
    parser.add_argument(
        "--config",
        default=str(default_openclaw_config_path()),
        help="openclaw.json 路径",
    )
    args = parser.parse_args()

    result = resolve_install_params(
        args.agent_id,
        Path(args.path).expanduser().resolve(),
        Path(args.config).expanduser().resolve(),
    )
    json.dump(result, sys.stdout, indent=2, ensure_ascii=False)
    sys.stdout.write("\n")
    return 0


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