"""Secrets management via Pulumi ESC."""

import json
import subprocess
from functools import lru_cache


@lru_cache(maxsize=1)
def _load_environment() -> dict[str, str]:
    """Load secrets from Pulumi ESC environment."""
    try:
        result = subprocess.run(
            ["esc", "env", "open", "beanflows/prod", "--format", "json"],
            capture_output=True,
            text=True,
            check=True,
        )
        data = json.loads(result.stdout)
        return data.get("environmentVariables", {})
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f"Failed to load ESC environment: {e.stderr}")
    except FileNotFoundError:
        raise RuntimeError("ESC CLI not found. Install with: curl -fsSL https://get.pulumi.com/esc/install.sh | sh")


def get_secret(key: str) -> str | None:
    """Get a secret value by key."""
    env = _load_environment()
    return env.get(key)


def list_secrets() -> list[str]:
    """List all available secret keys."""
    env = _load_environment()
    return list(env.keys())


def test_connection() -> bool:
    """Test ESC connection."""
    try:
        _load_environment()
        return True
    except Exception:
        return False
