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

import argparse
import json
import sys
from pathlib import Path

from common import markdown_files_in_dir, read_agent_placeholders, resolve_agent_directory


def parse_replacements(values: list[str]) -> dict[str, str]:
    replacements: dict[str, str] = {}
    for value in values:
        if "=" not in value:
            raise ValueError(f"replace 参数格式错误: {value}")
        key, raw_replacement = value.split("=", 1)
        placeholder = key.strip()
        replacement = raw_replacement.strip()
        if not placeholder or not replacement:
            raise ValueError(f"replace 参数格式错误: {value}")
        replacements[placeholder] = replacement
    return replacements


def update_agent_md(agent_id: str, source_path: Path, replacements: dict[str, str]) -> dict[str, object]:
    agent_dir = resolve_agent_directory(agent_id, source_path)
    md_files = markdown_files_in_dir(agent_dir)
    placeholders = read_agent_placeholders(agent_id, source_path)
    updated_files: list[str] = []

    for md_path in md_files:
        original = md_path.read_text(encoding="utf-8")
        updated = original
        for placeholder, replacement in replacements.items():
            updated = updated.replace(placeholder, replacement)
        if updated != original:
            md_path.write_text(updated, encoding="utf-8")
            updated_files.append(md_path.name)

    return {
        "ok": True,
        "agent_id": agent_id,
        "agent_directory": str(agent_dir),
        "placeholders": placeholders,
        "replacements": replacements,
        "updated_files": updated_files,
        "message": "Agent 模板中的占位（placeholder_catalog / token）替换完成。",
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="按 token 替换 Agent 模板 .md（见 placeholder_catalog）")
    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(
        "--replace",
        action="append",
        default=[],
        help='token 替换，格式如 --replace "{{客服助手}}=客服助手A"（token 与配置侧 label 见 placeholder_catalog）',
    )
    args = parser.parse_args()

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


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