from __future__ import annotations
import importlib
import logging
from typing import Optional

log = logging.getLogger(__name__)


class CLR:
    _loaded: bool = False
    _error: Optional[Exception] = None

    @classmethod
    def is_available(cls) -> bool:
        try:
            importlib.import_module("clr")
            return True
        except Exception:
            return False

    @classmethod
    def ensure_initialized(cls) -> bool:
        if cls._loaded:
            return True
        try:
            import clr  # type: ignore
            cls._loaded = True
            return True
        except Exception as e:
            cls._error = e
            log.debug("pythonnet 'clr' not available: %s", e)
            return False

    @classmethod
    def add_reference(cls, path: str) -> bool:
        if not cls.ensure_initialized():
            return False
        try:
            import clr  # type: ignore
            clr.AddReference(path)  # type: ignore
            return True
        except Exception as e:
            cls._error = e
            log.debug("clr.AddReference(%s) failed: %s", path, e)
            return False

    @classmethod
    def last_error(cls) -> Optional[Exception]:
        return cls._error