"""
校验智能培训系统安装状态。

三种状态（退出码）：
  0 — INSTALLED：已安装，无需操作
  1 — NOT_INSTALLED：未安装
  2 — UPDATABLE：可更新

同时输出配置状态（CONFIG_FOUND / CONFIG_NOT_FOUND）。
当状态为 UPDATABLE 且配置存在时，额外输出已有的 ADMIN_NAME / QA_NAME。
"""

import argparse
import json
import os
import sys


def get_workspace_root(config_path: str) -> str:
    """从 openclaw.json 所在目录推导 workspace 根目录（.openclaw）。"""
    return os.path.dirname(os.path.abspath(config_path))


def step2_artifacts_exist(workspace_root: str) -> bool:
    """检查 Step 2 要创建的目录和软链接是否已存在。"""
    base = os.path.join(workspace_root, "workspace-training")
    workspace_qa = os.path.join(base, "workspace-qa")

    if not os.path.isdir(workspace_qa):
        return False

    return True


def agents_already_in_config(config_path: str) -> bool:
    """检查 openclaw.json 中是否已包含 training-admin 和 training-qa。"""
    if not os.path.exists(config_path):
        return False
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            config = json.load(f)
    except (json.JSONDecodeError, OSError):
        return False
    agents = config.get("agents", {}).get("list", [])
    ids = {a.get("id") for a in agents if isinstance(a, dict) and a.get("id")}
    return "training-admin" in ids and "training-qa" in ids


def get_agent_names(config_path: str) -> tuple[str, str]:
    """从 openclaw.json 读取 training-admin 和 training-qa 的显示名称。"""
    admin_name, qa_name = "培训管理员", "培训助手"
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            config = json.load(f)
        for agent in config.get("agents", {}).get("list", []):
            if not isinstance(agent, dict):
                continue
            if agent.get("id") == "training-admin" and agent.get("name"):
                admin_name = agent["name"]
            elif agent.get("id") == "training-qa" and agent.get("name"):
                qa_name = agent["name"]
    except (json.JSONDecodeError, OSError):
        pass
    return admin_name, qa_name


def parse_version(v: str) -> tuple:
    """将版本号字符串解析为可比较的整数元组。"""
    try:
        return tuple(int(x) for x in v.strip().split("."))
    except (ValueError, AttributeError):
        return ()


def get_installed_version(workspace_root: str) -> str | None:
    """读取 workspace-training/git_version 中的版本号。"""
    version_file = os.path.join(workspace_root, "workspace-training", "git_version")
    if not os.path.isfile(version_file):
        return None
    try:
        with open(version_file, "r", encoding="utf-8") as f:
            return f.read().strip()
    except OSError:
        return None


def check_installed(config_path: str, target_version: str) -> int:
    """
    判断安装状态。
    返回: 0=已安装, 1=未安装, 2=可更新
    """
    workspace_root = get_workspace_root(config_path)

    if not step2_artifacts_exist(workspace_root):
        return 1

    installed_version = get_installed_version(workspace_root)
    if installed_version is None or parse_version(installed_version) < parse_version(target_version):
        return 2

    if not agents_already_in_config(config_path):
        return 1

    return 0


def main():
    parser = argparse.ArgumentParser(description="校验智能培训系统安装状态")
    parser.add_argument(
        "--config",
        default="/home/node/.openclaw/openclaw.json",
        help="openclaw.json 路径",
    )
    parser.add_argument(
        "--version",
        required=True,
        help="目标版本号（例：1.0.1）",
    )
    args = parser.parse_args()

    config_path = args.config
    status = check_installed(config_path, args.version)
    config_exists = agents_already_in_config(config_path)

    if status == 0:
        print("INSTALLED")
        print("CONFIG_FOUND" if config_exists else "CONFIG_NOT_FOUND")
        sys.exit(0)
    elif status == 2:
        print("UPDATABLE")
        print("CONFIG_FOUND" if config_exists else "CONFIG_NOT_FOUND")
        if config_exists:
            admin_name, qa_name = get_agent_names(config_path)
            print(f"ADMIN_NAME={admin_name}")
            print(f"QA_NAME={qa_name}")
        sys.exit(2)
    else:
        print("NOT_INSTALLED")
        print("CONFIG_FOUND" if config_exists else "CONFIG_NOT_FOUND")
        sys.exit(1)


if __name__ == "__main__":
    main()
