# Copyright 2026 Guildhouse Dev
# SPDX-License-Identifier: Apache-2.0

"""Registrar factory — selects the appropriate AgentRegistrar based on settings."""

import logging

from .base import AgentRegistrar
from .stub import StubRegistrar

logger = logging.getLogger(__name__)


def create_registrar(config) -> AgentRegistrar:
    """Create the appropriate registrar based on agent_registrar setting."""
    driver = config.agent_registrar

    if driver == "stub":
        return StubRegistrar()

    if driver == "keycloak":
        if not config.keycloak_admin_client_secret:
            logger.warning("Keycloak secret not configured, using stub")
            return StubRegistrar()
        from .keycloak import KeycloakRegistrar
        return KeycloakRegistrar(
            base_url=config.keycloak_url,
            realm=config.keycloak_realm,
            client_id=config.keycloak_admin_client_id,
            client_secret=config.keycloak_admin_client_secret,
        )

    if driver == "entra":
        if not config.entra_client_secret:
            logger.warning("Entra secret not configured, using stub")
            return StubRegistrar()
        from gsap_broker.intune.graph_client import GraphClient
        from .entra import EntraRegistrar
        graph = GraphClient(
            tenant_id=config.entra_tenant_id,
            client_id=config.entra_client_id,
            client_secret=config.entra_client_secret,
        )
        return EntraRegistrar(
            graph_client=graph,
            agent_blueprint_id=config.entra_agent_blueprint_id,
        )

    if driver == "auto":
        if config.entra_client_secret:
            from gsap_broker.intune.graph_client import GraphClient
            from .entra import EntraRegistrar
            logger.info("Auto-selected Entra registrar")
            graph = GraphClient(
                tenant_id=config.entra_tenant_id,
                client_id=config.entra_client_id,
                client_secret=config.entra_client_secret,
            )
            return EntraRegistrar(
                graph_client=graph,
                agent_blueprint_id=config.entra_agent_blueprint_id,
            )
        if config.keycloak_admin_client_secret:
            from .keycloak import KeycloakRegistrar
            logger.info("Auto-selected Keycloak registrar")
            return KeycloakRegistrar(
                base_url=config.keycloak_url,
                realm=config.keycloak_realm,
                client_id=config.keycloak_admin_client_id,
                client_secret=config.keycloak_admin_client_secret,
            )
        logger.warning("No IdP configured, using stub registrar")
        return StubRegistrar()

    logger.warning("Unknown registrar driver: %s, using stub", driver)
    return StubRegistrar()
