"""Profile-to-Apollo-credentials mapping via AWS Secrets Manager."""

from __future__ import annotations

import json

import boto3
from botocore.exceptions import ClientError

from cube_cloud.config import settings


def get_credentials(profile: str) -> tuple[str, str]:
    """Get Apollo client_id and client_secret for a profile.

    Reads from Secrets Manager at: {prefix}{profile}
    Secret value JSON: {"client_id": "...", "client_secret": "..."}

    Returns (client_id, client_secret). Raises ValueError if not found.
    """
    client = boto3.client("secretsmanager", region_name=settings.aws_region)
    secret_name = f"{settings.secrets_prefix}{profile}"

    try:
        resp = client.get_secret_value(SecretId=secret_name)
    except ClientError as e:
        code = e.response["Error"]["Code"]
        if code in ("ResourceNotFoundException", "AccessDeniedException"):
            raise ValueError(f"No credentials found for profile '{profile}'") from e
        raise

    secret = json.loads(resp["SecretString"])
    client_id = secret.get("client_id", "")
    client_secret = secret.get("client_secret", "")

    if not client_id or not client_secret:
        raise ValueError(f"Profile '{profile}' secret is missing client_id or client_secret")

    return client_id, client_secret
