"""CGT License SDK -- Python wrapper for Guard.dll."""

__version__ = "0.2.3"

from ._guard import (
    GuardFFI,
    LicenseError,
    InvalidKeyError,
    MaxDevicesError,
    ProductMismatchError,
    NetworkError,
    NotInitializedError,
    NoSecretError,
    DecryptError,
)
from .bootstrap import bootstrap

# Global guard instance, set by bootstrap
_guard_instance: GuardFFI | None = None


def get_guard() -> GuardFFI:
    """Get the bootstrapped guard instance."""
    if _guard_instance is None:
        raise NotInitializedError(
            "License not bootstrapped. Add 'import cgt_license_bootstrap' "
            "at the top of your entrypoint."
        )
    return _guard_instance


def decrypt_asset(encrypted: bytes) -> bytes:
    """Decrypt an encrypted asset file using the runtime secret.

    The runtime secret is held by Guard.dll and was obtained during lease.
    Key derivation: HKDF-SHA256(runtime_secret, salt="cgt-asset", info=product_id)
    Cipher: AES-256-GCM
    Format: nonce(12) + ciphertext + tag(16)
    """
    return get_guard().decrypt_asset(encrypted)


def get_features() -> dict[str, bool] | None:
    """Get current feature flags from the last lease/renew response.

    Returns a dict like {"ai_clip": True, "cloud_sync": False},
    or None if no features are configured for the product.

    Features are automatically updated every time the watchdog
    renews the lease (~10 minutes).
    """
    return get_guard().get_features()


def is_feature_enabled(name: str, default: bool = False) -> bool:
    """Check if a specific feature is enabled.

    Args:
        name: Feature name (e.g. "ai_clip", "batch_export")
        default: Value to return if features are not configured
                 on the server (features=None), or if the feature
                 name is not found. Defaults to False.

    Returns:
        True if the feature is enabled, False otherwise.
    """
    features = get_features()
    if features is None:
        return default
    return features.get(name, default)
