"""Auto-discover release on boot (non-interactive connect)."""

from __future__ import annotations

import logging
import os

from ilum.api.deps import set_manager
from ilum.config.manager import ConfigManager
from ilum.config.paths import IlumPaths
from ilum.constants import (
    DEFAULT_CHART_REF,
    DEFAULT_NAMESPACE,
    DEFAULT_RELEASE_NAME,
    is_local_chart,
)
from ilum.core.helm import HelmClient
from ilum.core.kubernetes import KubeClient
from ilum.core.modules import ModuleResolver
from ilum.core.release import ReleaseManager

logger = logging.getLogger(__name__)


def auto_connect() -> None:
    """Build a ReleaseManager from environment or auto-detection.

    Uses ``ILUM_RELEASE_NAME`` and ``ILUM_NAMESPACE`` when set, otherwise
    falls back to scanning for releases via ``ReleaseManager.scan_releases()``.
    """
    release_name = os.environ.get("ILUM_RELEASE_NAME", "")
    namespace = os.environ.get("ILUM_NAMESPACE", DEFAULT_NAMESPACE)
    context = os.environ.get("ILUM_KUBE_CONTEXT", "")

    paths = IlumPaths.default()
    paths.ensure_dirs()

    mgr = ReleaseManager(
        helm=HelmClient(kubecontext=context, namespace=namespace),
        k8s=KubeClient(kubecontext=context),
        resolver=ModuleResolver(),
        config_mgr=ConfigManager(paths),
        paths=paths,
    )

    if not release_name:
        releases = mgr.scan_releases(namespace=namespace)
        if releases:
            release_name = releases[0].name
            namespace = releases[0].namespace
            # Rebuild with correct namespace if changed
            if namespace != mgr.helm.namespace:
                mgr = ReleaseManager(
                    helm=HelmClient(kubecontext=context, namespace=namespace),
                    k8s=KubeClient(kubecontext=context),
                    resolver=ModuleResolver(),
                    config_mgr=ConfigManager(paths),
                    paths=paths,
                )
            logger.info("Auto-detected release '%s' in namespace '%s'", release_name, namespace)
        else:
            logger.warning(
                "No Ilum releases found. Using defaults: %s/%s",
                DEFAULT_NAMESPACE,
                DEFAULT_RELEASE_NAME,
            )

    os.environ.setdefault("ILUM_RELEASE_NAME", release_name or DEFAULT_RELEASE_NAME)
    os.environ.setdefault("ILUM_NAMESPACE", namespace)

    set_manager(mgr)

    # Recover operations from Kubernetes Jobs that survived a restart
    try:
        from ilum.api.job_runner import recover_operations
        from ilum.api.operations import get_operation_store

        store = get_operation_store()
        count = recover_operations(mgr.k8s, store, namespace)
        if count:
            logger.info("Recovered %d operation(s) from Kubernetes Jobs", count)
    except Exception:
        logger.exception("Failed to recover operations from Kubernetes Jobs")

    # Ensure Helm repo is configured (skip for local/bundled charts)
    chart_ref = os.environ.get("ILUM_CHART_REF", DEFAULT_CHART_REF)
    if not is_local_chart(chart_ref):
        try:
            mgr.ensure_repo()
        except Exception:
            logger.warning("Failed to configure Helm repo — remote chart operations may fail")
    else:
        logger.info("Using local chart at %s — skipping repo setup", chart_ref)

    logger.info("Ilum API connected: release=%s namespace=%s", release_name, namespace)

    # Auto-recover if the release is stuck from a prior interrupted operation
    from ilum.api.job_runner import has_any_helm_job

    effective_release = release_name or DEFAULT_RELEASE_NAME
    try:
        if has_any_helm_job(mgr.k8s, namespace):
            logger.info(
                "Skipping auto-recovery — ilum-api helm Job(s) exist in namespace '%s'",
                namespace,
            )
        elif mgr.is_stuck(effective_release):
            logger.warning(
                "Release '%s' is stuck — attempting auto-recovery via rollback",
                effective_release,
            )
            mgr.helm.rollback(effective_release)
            logger.info("Auto-recovered stuck release '%s' on startup", effective_release)
    except Exception:
        logger.exception(
            "Failed to auto-recover stuck release '%s' on startup. "
            "Manual recovery may be needed: helm rollback %s",
            effective_release,
            effective_release,
        )
