"""alice get-secret — Get a secret by short name (auto-prefixes namespace/environment)."""

from __future__ import annotations

import boto3
import click
from botocore.exceptions import ClientError

from alice_cli import personality
from alice_cli.auth import detect_username
from alice_cli.console import print_banner, print_status, print_success
from alice_cli.errors import AliceCLIError
from alice_cli.secrets import is_secret_owned_by_user


def build_short_name_path(namespace: str, environment: str, short_name: str) -> str:
    """Construct the full secret path from a short name.

    Args:
        namespace: Organizational prefix (e.g. "drcc").
        environment: Deployment stage (e.g. "ai").
        short_name: The short secret name provided by the user.

    Returns:
        The full secret path: {namespace}/{environment}/{short_name}
    """
    return f"{namespace}/{environment}/{short_name}"


def _check_bedrock_access(full_path: str, username: str) -> None:
    """Enforce user-scoped access for bedrock-api-keys secrets.

    Raises:
        AliceCLIError: If the secret belongs to a different user.
    """
    if not is_secret_owned_by_user(full_path, username):
        raise AliceCLIError("Access denied — you can only view your own secrets.")


@click.command("get-secret")
@click.argument("name", required=False, default=None)
@click.pass_context
def get_secret(ctx: click.Context, name: str | None) -> None:
    """Retrieve a secret by short name.

    Automatically prefixes with namespace/environment. When NAME is omitted,
    fetches your own Bedrock API key.
    """
    config = ctx.obj["config"]

    print_banner(personality.BANNER, config.quiet)

    # Detect the current user's JHED for access control
    username_result = detect_username(config.profile, config.region)

    # Default to the user's own bedrock-api-key when no name is given
    if name is None:
        name = f"bedrock-api-keys/{username_result.username}@jhu.edu"

    # Build full secret path from short name
    full_path = build_short_name_path(config.namespace, config.environment, name)

    # Enforce user-scoped access for bedrock-api-keys
    _check_bedrock_access(full_path, username_result.username)

    print_status(f"Fetching secret: {full_path}", config.quiet)

    # Create boto3 session and fetch the secret
    session = boto3.Session(profile_name=config.profile, region_name=config.region)
    client = session.client("secretsmanager")

    try:
        response = client.get_secret_value(SecretId=full_path)
    except ClientError as exc:
        raise AliceCLIError(personality.error_secret_not_found(full_path)) from exc

    secret_value = response["SecretString"]
    print_success(f"Secret retrieved: {full_path}", config.quiet)
    click.echo(secret_value)
