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

import argparse
import json
import sys
from pathlib import Path

from common import load_json


REQUIRED_FILES = [
    ".config.json",
    "AGENTS.md",
    "BOOTSTRAP.md",
    "IDENTITY.md",
    "SOUL.md",
    "TOOLS.md",
    "USER.md",
]


def inspect_candidate(agent_id: str, directory: Path) -> dict[str, object]:
    config_path = directory / ".config.json"
    if not config_path.is_file():
        return {
            "directory": str(directory),
            "ok": False,
            "reason": "config_missing",
        }

    try:
        config = load_json(config_path)
    except Exception as exc:  # noqa: BLE001
        return {
            "directory": str(directory),
            "ok": False,
            "reason": "config_invalid",
            "error": str(exc),
        }

    config_agent_id = config.get("agent_id")
    missing_files = [name for name in REQUIRED_FILES if not (directory / name).is_file()]
    missing_fields = [name for name in ("agent_id", "version", "workspace", "agent_dependencies") if name not in config]

    if config_agent_id != agent_id:
        return {
            "directory": str(directory),
            "ok": False,
            "reason": "agent_id_mismatch",
            "config_agent_id": config_agent_id,
            "missing_files": missing_files,
            "missing_fields": missing_fields,
        }

    if missing_fields:
        return {
            "directory": str(directory),
            "ok": False,
            "reason": "config_fields_missing",
            "config_agent_id": config_agent_id,
            "missing_files": missing_files,
            "missing_fields": missing_fields,
        }

    if missing_files:
        return {
            "directory": str(directory),
            "ok": False,
            "reason": "required_files_missing",
            "config_agent_id": config_agent_id,
            "missing_files": missing_files,
            "missing_fields": missing_fields,
        }

    return {
        "directory": str(directory),
        "ok": True,
        "reason": "valid",
        "config_agent_id": config_agent_id,
        "version": config.get("version"),
        "workspace": config.get("workspace"),
        "agent_dependencies": config.get("agent_dependencies", []),
        "missing_files": [],
        "missing_fields": [],
    }


def candidate_directories(download_path: Path, agent_id: str) -> list[Path]:
    candidates = [download_path / agent_id, download_path]
    unique: list[Path] = []
    seen: set[str] = set()
    for candidate in candidates:
        resolved = str(candidate)
        if resolved not in seen:
            unique.append(candidate)
            seen.add(resolved)
    return unique


def verify_download(agent_id: str, download_path: Path) -> dict[str, object]:
    inspections = []
    for directory in candidate_directories(download_path, agent_id):
        inspections.append(inspect_candidate(agent_id, directory))

    valid = next((item for item in inspections if item["ok"]), None)
    if valid:
        return {
            "ok": True,
            "agent_id": agent_id,
            "download_path": str(download_path),
            "agent_directory": valid["directory"],
            "version": valid["version"],
            "workspace": valid["workspace"],
            "agent_dependencies": valid["agent_dependencies"],
            "message": "Agent 下载成功，关键配置文件校验通过。",
            "inspections": inspections,
        }

    first_error = inspections[0] if inspections else {"reason": "unknown"}
    return {
        "ok": False,
        "agent_id": agent_id,
        "download_path": str(download_path),
        "message": "Agent 下载结果校验失败，请检查下载目录和 Agent 包内容。",
        "reason": first_error.get("reason"),
        "inspections": inspections,
    }


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="sophhub agent download 使用的目标目录",
    )
    args = parser.parse_args()

    result = verify_download(args.agent_id, Path(args.path).expanduser().resolve())
    json.dump(result, sys.stdout, indent=2, ensure_ascii=False)
    sys.stdout.write("\n")
    return 0 if result["ok"] else 1


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