from __future__ import annotations

from typing import Any

from govoplan_core.core.modules import ModuleContext

_context: ModuleContext | None = None


def configure_runtime(context: ModuleContext) -> None:
    global _context
    _context = context


def clear_runtime() -> None:
    global _context
    _context = None


def get_runtime_context() -> ModuleContext | None:
    return _context


def get_registry() -> object | None:
    return _context.registry if _context is not None else None


class ModuleSettingsProxy:
    def __init__(self, runtime: ModuleRuntimeState) -> None:
        self._runtime = runtime

    def __getattr__(self, name: str) -> Any:
        return getattr(self._runtime.get_settings(), name)


class ModuleRuntimeState:
    def __init__(self, module_name: str) -> None:
        self.module_name = module_name
        self.settings = ModuleSettingsProxy(self)
        self._registry: object | None = None
        self._settings: object | None = None

    def configure_runtime(self, *, registry: object | None = None, settings: object | None = None) -> None:
        if registry is not None:
            self._registry = registry
        if settings is not None:
            self._settings = settings

    def clear_runtime(self) -> None:
        self._registry = None
        self._settings = None

    def get_registry(self) -> object | None:
        return self._registry

    def get_settings(self) -> object:
        if self._settings is not None:
            return self._settings
        try:
            from govoplan_core.settings import settings as legacy_settings
        except ModuleNotFoundError as exc:
            raise RuntimeError(f"GovOPlaN {self.module_name} runtime settings are not configured") from exc
        return legacy_settings
