"""alice export — Export Bedrock credentials as environment variables."""

from __future__ import annotations

import click

from alice_cli import personality
from alice_cli.auth import detect_username
from alice_cli.console import print_banner, print_status, print_success, spinner
from alice_cli.formatting import format_credentials
from alice_cli.models import OutputFormat
from alice_cli.secrets import build_secret_path, fetch_credentials

_FMT_MAP: dict[str, OutputFormat] = {
    "eval": OutputFormat.EVAL,
    "dotenv": OutputFormat.DOTENV,
    "json": OutputFormat.JSON,
}


@click.command("export")
@click.option("--eval", "fmt", flag_value="eval", help="Eval-ready output")
@click.option("--env-file", "fmt", flag_value="dotenv", help="Dotenv format")
@click.option("--json", "fmt", flag_value="json", help="Raw JSON")
@click.pass_context
def get_key(ctx: click.Context, fmt: str | None) -> None:
    """Print Bedrock credentials as environment variables."""
    config = ctx.obj["config"]

    # 1. Banner
    print_banner(personality.BANNER, config.quiet)

    # 2. Detect identity
    with spinner(personality.status_detecting_identity(), config.quiet):
        result = detect_username(config.profile, config.region)
    print_status(personality.status_identity_detected(result.username), config.quiet)

    # 3. Build secret path and fetch credentials
    secret_path = build_secret_path(config.namespace, config.environment, result.username)
    with spinner(personality.status_fetching_secret(), config.quiet):
        creds = fetch_credentials(config.profile, config.region, secret_path)

    # 4. Success
    print_success(personality.SUCCESS_KEY_RETRIEVED, config.quiet)

    # 5. Determine output format (default: EXPORT)
    output_format = _FMT_MAP.get(fmt, OutputFormat.EXPORT) if fmt else OutputFormat.EXPORT

    # 6. Format and write to stdout
    output = format_credentials(creds, output_format, result.username, result.session_name)
    click.echo(output, nl=False)
