"""Key resolution helpers for Mira."""

from __future__ import annotations

import getpass
import os


def read_key_file(path: str) -> str:
    """Read a secret key from a file."""
    with open(path, "r", encoding="utf-8") as handle:
        return handle.read().strip()


def resolve_secret(
    value: str | None,
    key_file: str | None,
    env_var: str | None,
    env_file_var: str | None,
    prompt: bool = False,
    label: str = "key",
) -> str | None:
    """Resolve a secret from explicit value, file, env, or prompt.

    Args:
        value: Explicit secret value.
        key_file: Path to a file containing the secret.
        env_var: Environment variable name containing the secret.
        env_file_var: Environment variable pointing to a secret file.
        prompt: Whether to prompt interactively if no secret is found.
        label: Label used in the prompt message.

    Returns:
        The resolved secret, or None if not found.
    """
    if value:
        return value
    if key_file:
        return read_key_file(key_file)
    if env_var:
        env_value = os.environ.get(env_var)
        if env_value:
            return env_value
    if env_file_var:
        env_file = os.environ.get(env_file_var)
        if env_file:
            return read_key_file(env_file)
    if prompt:
        try:
            secret = getpass.getpass(f"Enter {label}: ")
        except (EOFError, KeyboardInterrupt):
            return None
        return secret.strip() if secret else None
    return None
