"""Dynamic installer submodules.

Important: `armorer.installers.dynamic` is now a package (directory) but the
existing monolith entrypoint still lives in the sibling file
`src/armorer/installers/dynamic.py`.

To avoid breaking imports (`from armorer.installers.dynamic import
DynamicInstaller`), we dynamically load that sibling module and re-export
`DynamicInstaller`.
"""

from __future__ import annotations

import importlib.util
import sys
from pathlib import Path
import types

_HERE = Path(__file__).resolve()
_DYNAMIC_PY = _HERE.parent.parent / "dynamic.py"

_MODULE_NAME = "armorer.installers._dynamic_entrypoint"
if _MODULE_NAME in sys.modules:
    _mod = sys.modules[_MODULE_NAME]
else:
    _spec = importlib.util.spec_from_file_location(_MODULE_NAME, _DYNAMIC_PY)
    if _spec is None or _spec.loader is None:  # pragma: no cover
        raise ImportError(f"Unable to load DynamicInstaller entrypoint from {_DYNAMIC_PY}")
    _mod = importlib.util.module_from_spec(_spec)
    sys.modules[_MODULE_NAME] = _mod
    _spec.loader.exec_module(_mod)

DynamicInstaller = _mod.DynamicInstaller  # type: ignore[attr-defined]

# Back-compat for tests/legacy code that monkeypatch this symbol.
_LiveLogPanel = getattr(_mod, "_LiveLogPanel", None)

# Re-export monolith symbols so existing tests can monkeypatch via
# `armorer.installers.dynamic.<symbol>`.
for _k, _v in list(_mod.__dict__.items()):
    if _k.startswith("__"):
        continue
    globals()[_k] = _v

__all__ = [k for k in globals().keys() if not k.startswith("__")]


class _DynamicPackageProxy(types.ModuleType):
    """Forward attribute writes to the loaded monolith module.

    This is important for unit tests that use `monkeypatch.setattr` on
    `armorer.installers.dynamic.<symbol>` but expect the dynamically loaded
    entrypoint (`armorer.installers._dynamic_entrypoint`) to observe the change.
    """

    def __getattr__(self, name: str):  # pragma: no cover
        return getattr(_mod, name)

    def __setattr__(self, name: str, value):  # type: ignore[override]
        setattr(_mod, name, value)
        super().__setattr__(name, value)


# Swap the current module's type to enable `setattr()` forwarding.
sys.modules[__name__].__class__ = _DynamicPackageProxy

