#!/usr/bin/env python3
"""校验中台 Skill 注册表与设备端 Skill 类 public method 对齐"""

from __future__ import annotations

import inspect
import json
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "app"))
sys.path.insert(0, str(ROOT / "agent"))

from services.brain_skill_registry import DEVICE_EXECUTABLE_SCRIPTS, SKILL_REGISTRY, flatten_actions  # noqa: E402

SKIP_METHODS = frozenset({
    "execute_compound_task", "send_message_with_vision", "send_message_with_search",
    "get_current_screen_info",
})


def _public_methods(cls) -> set[str]:
    return {
        n for n, m in inspect.getmembers(cls, predicate=inspect.isfunction)
        if not n.startswith("_") and n not in SKIP_METHODS
    }


def main() -> int:
    from skills import get_skill  # noqa: WPS433

    missing_on_device: list[str] = []
    extra_on_device: list[str] = []
    ok = 0

    for script in sorted(DEVICE_EXECUTABLE_SCRIPTS):
        registry_actions = set(flatten_actions(script))
        try:
            cls = get_skill(script)
        except ImportError as e:
            print(f"❌ {script}: 无法加载 Skill 类: {e}")
            return 1
        device_actions = _public_methods(cls)
        for action in sorted(registry_actions):
            if action not in device_actions:
                missing_on_device.append(f"{script}.{action}")
            else:
                ok += 1
        for action in sorted(device_actions - registry_actions):
            extra_on_device.append(f"{script}.{action}")

    report = {
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
        "registry_actions_checked": ok,
        "missing_on_device": missing_on_device,
        "extra_on_device_not_in_registry": extra_on_device,
        "complete": len(missing_on_device) == 0,
    }
    out = ROOT / "tmp" / f"skill_registry_audit_{int(time.time())}.json"
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")

    print(f"registry 校验 action 数: {ok}")
    print(f"设备缺失: {len(missing_on_device)}")
    print(f"注册表未收录(设备有): {len(extra_on_device)}")
    if missing_on_device:
        print("缺失示例:", missing_on_device[:10])
    if extra_on_device:
        print("未收录示例:", extra_on_device[:10])
    print("完整对齐:", "✅" if report["complete"] else "❌")
    print("报告:", out)
    return 0 if report["complete"] else 1


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