"""Check Core connector actions against the P2HS Cloud action registry.

Usage from the Core repository:

    python tools/check_connector_action_parity.py
    python tools/check_connector_action_parity.py --cloud-root E:/workroom/2026/P2HSCloud
"""
from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from src.domain.connectors.catalog import CONNECTORS

ACTION_LITERAL = re.compile(r'"([a-z0-9_]+\.[a-z0-9_]+)"')
ACTION_KEY_LINE = re.compile(r"action_key\s*:")
ACTION_MAP_LINE = re.compile(r'^\s*"[a-z0-9_]+\.[a-z0-9_]+"\s*:')


def core_action_slugs() -> set[str]:
    return {action.slug for connector in CONNECTORS.values() for action in connector.actions}


def cloud_action_slugs(cloud_root: Path) -> set[str]:
    connector_dir = cloud_root / "apps" / "pc-processor" / "src" / "handlers" / "connectors"
    if not connector_dir.is_dir():
        raise FileNotFoundError(f"Cloud connector directory not found: {connector_dir}")

    found: set[str] = set()
    for path in connector_dir.glob("*.ts"):
        for line in path.read_text(encoding="utf-8").splitlines():
            if ACTION_KEY_LINE.search(line) or ACTION_MAP_LINE.search(line):
                found.update(ACTION_LITERAL.findall(line))
    return found


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--cloud-root",
        type=Path,
        default=Path(__file__).resolve().parents[2] / "P2HSCloud",
    )
    args = parser.parse_args()

    core = core_action_slugs()
    cloud = cloud_action_slugs(args.cloud_root)
    core_missing = sorted(core - cloud)
    cloud_missing = sorted(cloud - core)
    if core_missing or cloud_missing:
        if core_missing:
            print("Core actions missing from Cloud:")
            print("\n".join(f"  {slug}" for slug in core_missing))
        if cloud_missing:
            print("Cloud actions missing from Core:")
            print("\n".join(f"  {slug}" for slug in cloud_missing))
        return 1

    print(f"Connector action parity OK ({len(core)} actions)")
    return 0


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