"""Bootstrap an :class:`A2aLocalFacade` wired to the DI container.

CLI commands that need to route operations through the A2A facade
call :func:`get_facade` to obtain a lazily-constructed, fully-wired
facade instance.  The facade is cached per-process so repeated CLI
invocations within the same Python process share services.

Usage::

    from cleveragents.a2a.cli_bootstrap import get_facade
    from cleveragents.a2a.models import A2aRequest

    facade = get_facade()
    response = facade.dispatch(
        A2aRequest(method="session.create", params={"actor": "stub"})
    )
"""

from __future__ import annotations

from typing import Any

from cleveragents.a2a.facade import A2aLocalFacade

_facade_instance: A2aLocalFacade | None = None


def _build_facade() -> A2aLocalFacade:
    """Construct a facade wired to real application services."""
    import contextlib

    from cleveragents.application.container import get_container

    container = get_container()
    services: dict[str, Any] = {}

    # Wire available services — each key is optional so the facade
    # gracefully stubs operations when a service is absent.
    with contextlib.suppress(Exception):
        services["plan_lifecycle_service"] = container.plan_lifecycle_service()

    with contextlib.suppress(Exception):
        services["session_service"] = container.session_service()

    with contextlib.suppress(Exception):
        services["resource_registry_service"] = container.resource_registry_service()

    with contextlib.suppress(Exception):
        services["tool_registry"] = container.tool_registry()

    return A2aLocalFacade(services=services)


def get_facade() -> A2aLocalFacade:
    """Return the process-wide :class:`A2aLocalFacade` instance.

    The facade is lazily constructed on first call and cached for the
    lifetime of the process.
    """
    global _facade_instance
    if _facade_instance is None:
        _facade_instance = _build_facade()
    return _facade_instance


def reset_facade() -> None:
    """Reset the cached facade (useful for testing)."""
    global _facade_instance
    _facade_instance = None


__all__ = [
    "get_facade",
    "reset_facade",
]
