"""Auto-discovers all connector definitions in this package.

To add a new connector: create a .py file in this directory and set a
module-level `CONNECTOR` variable of type ConnectorDef. It will be picked
up automatically on next startup.
"""
from __future__ import annotations

import importlib
import pkgutil
from pathlib import Path
from typing import Optional

from src.domain.connectors.catalog._base import (
    ConnectorActionDef,
    ConnectorChangelogEntry,
    ConnectorDef,
    ConnectorFieldDef,
    ConnectorTriggerDef,
)

__all__ = [
    "CONNECTORS",
    "get_connector",
    "get_action",
    "slugs_implementing",
    "implements_for_slug",
    "supported_connectors",
    "ConnectorDef",
    "ConnectorActionDef",
    "ConnectorTriggerDef",
    "ConnectorChangelogEntry",
    "ConnectorFieldDef",
]

CONNECTORS: dict[str, ConnectorDef] = {}

for _finder, _mod_name, _ispkg in pkgutil.iter_modules([str(Path(__file__).parent)]):
    if _mod_name.startswith("_"):
        continue
    _module = importlib.import_module(f"{__name__}.{_mod_name}")
    if hasattr(_module, "CONNECTOR"):
        _c: ConnectorDef = _module.CONNECTOR
        CONNECTORS[_c.key] = _c


def get_connector(key: str) -> Optional[ConnectorDef]:
    return CONNECTORS.get(key)


def supported_connectors() -> list[str]:
    return list(CONNECTORS.keys())


def get_action(slug: str) -> tuple[ConnectorDef, ConnectorActionDef] | None:
    for connector in CONNECTORS.values():
        for action in connector.actions:
            if action.slug == slug:
                return connector, action
    return None


def slugs_implementing(capability: str) -> tuple[str, ...]:
    """Catalog-only: action slugs that implement a P2HS invoke capability."""
    found: list[str] = []
    for connector in CONNECTORS.values():
        for action in connector.actions:
            if capability in action.implements:
                found.append(action.slug)
    return tuple(found)


def implements_for_slug(slug: str) -> tuple[str, ...]:
    pair = get_action(slug)
    if not pair:
        return ()
    return pair[1].implements
