"""Resolve CLI option defaults from the active profile."""

from __future__ import annotations

from ilum.constants import DEFAULT_ACCESS_TYPE, DEFAULT_NAMESPACE, DEFAULT_RELEASE_NAME


def resolve_profile_defaults(
    release: str | None,
    namespace: str | None,
    context: str | None,
) -> tuple[str, str, str]:
    """Fill in release/namespace/context from the active profile when not provided.

    For each ``None`` value, the active profile is consulted first.  If the
    profile field is empty (or no config exists), the hardcoded constant is
    used as a final fallback.
    """
    if release is not None and namespace is not None and context is not None:
        return release, namespace, context

    # Lazy import to avoid circular deps and to keep the fast-path free of I/O.
    from ilum.config.manager import ConfigManager
    from ilum.config.paths import IlumPaths

    try:
        paths = IlumPaths.default()
        cfg = ConfigManager(paths).load()
        profile = cfg.profiles.get(cfg.active_profile)
    except Exception:  # noqa: BLE001
        profile = None

    if release is None:
        release = (
            profile.release_name if profile and profile.release_name else ""
        ) or DEFAULT_RELEASE_NAME

    if namespace is None:
        namespace = (
            profile.cluster.namespace if profile and profile.cluster.namespace else ""
        ) or DEFAULT_NAMESPACE

    if context is None:
        context = (profile.cluster.kubecontext if profile else "") or ""

    return release, namespace, context


def resolve_access_type(access: str | None) -> str:
    """Return the access type from CLI flag, profile, or default."""
    if access is not None:
        return access

    # Lazy import to avoid circular deps and to keep the fast-path free of I/O.
    from ilum.config.manager import ConfigManager
    from ilum.config.paths import IlumPaths

    try:
        paths = IlumPaths.default()
        cfg = ConfigManager(paths).load()
        profile = cfg.profiles.get(cfg.active_profile)
    except Exception:  # noqa: BLE001
        profile = None

    if profile and profile.access_type:
        return profile.access_type

    return DEFAULT_ACCESS_TYPE
