"""Public SDK API for programmatic access to brokr secrets."""

import os

from brokr.project import get_agent_secrets, get_project_secrets
from brokr.store import BrokrError, get_store_dir, load_store


def get(
    key: str,
    passphrase: str | None = None,
    agent: str | None = None,
    project: str | None = None,
) -> str:
    """Retrieve a secret from the brokr store.

    Args:
        key: Secret name to retrieve.
        passphrase: Store passphrase. Falls back to BROKR_PASSPHRASE env var.
        agent: If provided, enforce agent grant check. Requires project.
        project: If provided, enforce project membership check.

    Returns:
        The secret value.

    Raises:
        BrokrError: passphrase missing, or agent specified without project.
        KeyError: secret not found (or not linked to project).
        PermissionError: agent not granted access to secret.
    """
    if agent is not None and project is None:
        raise BrokrError(
            "project is required when agent is specified."
        )

    if passphrase is None:
        passphrase = os.environ.get("BROKR_PASSPHRASE")
    if passphrase is None:
        raise BrokrError(
            "No passphrase provided. Pass it explicitly or set BROKR_PASSPHRASE."
        )

    store_dir = get_store_dir()
    data = load_store(passphrase, store_dir=store_dir)

    if agent is not None and project is not None:
        agent_secrets = get_agent_secrets(data, project, agent)
        if key not in agent_secrets:
            raise PermissionError(
                f"Agent '{agent}' not granted access to '{key}' "
                f"in project '{project}'."
            )
        return agent_secrets[key]

    if project is not None:
        project_secrets = get_project_secrets(data, project)
        if key not in project_secrets:
            raise KeyError(
                f"Secret '{key}' not linked to project '{project}'."
            )
        return project_secrets[key]

    # Default: V1 behavior — return any secret
    secrets = data.get("secrets", {})
    if key not in secrets:
        raise KeyError(key)

    return secrets[key]
