"""Singleton cache for chart default values.

``helm show values`` is an expensive subprocess call that reads from
the chart repo.  Since the chart does not change during the API
process lifetime, we cache the result on first access.
"""

from __future__ import annotations

from io import StringIO
from typing import Any

from ruamel.yaml import YAML

from ilum.core.helm import HelmClient, HelmResult

_chart_defaults: dict[str, Any] | None = None


def get_chart_defaults(helm: HelmClient, chart_ref: str) -> dict[str, Any]:
    """Return cached chart defaults, fetching on first call.

    If ``helm show values`` fails (chart not in repo, network error,
    etc.) returns an empty dict — the schema generator falls back to
    computed values only.
    """
    global _chart_defaults  # noqa: PLW0603
    if _chart_defaults is None:
        try:
            result: HelmResult = helm.show_values(chart_ref)
            loader = YAML()
            parsed = loader.load(StringIO(result.stdout))
            _chart_defaults = dict(parsed) if parsed else {}
        except Exception:
            _chart_defaults = {}
    return _chart_defaults


def invalidate_chart_cache() -> None:
    """Clear the cached defaults (useful for testing)."""
    global _chart_defaults  # noqa: PLW0603
    _chart_defaults = None
