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

import argparse
import json
import shutil
import sys
from pathlib import Path

from common import resolve_agent_directory


def copy_entry(source: Path, target: Path) -> None:
    if source.is_dir():
        shutil.copytree(source, target, dirs_exist_ok=True)
    else:
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source, target)


def copy_agent_files(agent_id: str, source_path: Path, workspace: Path) -> dict[str, object]:
    agent_dir = resolve_agent_directory(agent_id, source_path)
    workspace.mkdir(parents=True, exist_ok=True)

    copied_entries: list[str] = []
    for source in sorted(agent_dir.iterdir()):
        target = workspace / source.name
        copy_entry(source, target)
        copied_entries.append(source.name)

    return {
        "ok": True,
        "agent_id": agent_id,
        "agent_directory": str(agent_dir),
        "workspace": str(workspace),
        "copied_entries": copied_entries,
        "message": "已将下载的 Agent 文件拷贝到目标 workspace（不包含最外层 Agent 文件夹）。",
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="拷贝下载的 Agent 文件到 workspace")
    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("--workspace", required=True, help="目标 workspace 路径")
    args = parser.parse_args()

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


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