"""Builtin plugin registry and protocol analyzer hooks."""

from __future__ import annotations

from collections.abc import Iterable

from sentra.models import ServiceEvidence
from sentra.plugins.base import ProtocolAnalyzer
from sentra.protocols.analyzers import (
    CoapAnalyzer,
    HttpBannerAnalyzer,
    MdnsAnalyzer,
    ModbusAnalyzer,
    MqttAnalyzer,
    SnmpAnalyzer,
    SsdpAnalyzer,
    TlsCertificateAnalyzer,
)

_PROTOCOL_ANALYZERS: list[ProtocolAnalyzer] = []


class InventoryPlugin:
    name = "inventory"

    def register(self) -> None:
        register_protocol_analyzer(HttpBannerAnalyzer())
        register_protocol_analyzer(MqttAnalyzer())
        register_protocol_analyzer(CoapAnalyzer())
        register_protocol_analyzer(TlsCertificateAnalyzer())
        register_protocol_analyzer(MdnsAnalyzer())
        register_protocol_analyzer(SsdpAnalyzer())
        register_protocol_analyzer(SnmpAnalyzer())
        register_protocol_analyzer(ModbusAnalyzer())


def register_protocol_analyzer(analyzer: ProtocolAnalyzer) -> None:
    if any(existing.name == analyzer.name for existing in _PROTOCOL_ANALYZERS):
        return
    _PROTOCOL_ANALYZERS.append(analyzer)


def get_protocol_analyzers() -> list[ProtocolAnalyzer]:
    return list(_PROTOCOL_ANALYZERS)


def reset_protocol_analyzers() -> None:
    _PROTOCOL_ANALYZERS.clear()


def apply_protocol_analyzers(host: str, service: ServiceEvidence) -> ServiceEvidence:
    enriched = service
    for analyzer in _PROTOCOL_ANALYZERS:
        candidate = analyzer.analyze(host, enriched)
        if candidate is not None:
            enriched = candidate
    return enriched


def get_builtin_plugins() -> list[InventoryPlugin]:
    return [InventoryPlugin()]

