"""Output formatters for Bedrock credentials."""

from __future__ import annotations

from alice_cli.models import (
    CLAUDE_DEFAULT_MODELS,
    DEFAULT_MODEL_ALIAS,
    CredentialSet,
    OutputFormat,
    resolve_model_id,
)

# Fixed credential constants
_CLAUDE_CODE_USE_BEDROCK = "1"


def format_credentials(
    creds: CredentialSet, fmt: OutputFormat, username: str, session_name: str
) -> str:
    """Render credentials in the requested output format."""
    if fmt is OutputFormat.JSON:
        return creds.raw_json

    arns = creds.inference_profile_arns

    vars_ = [
        # Claude Code auth (bearer token for Bedrock API key auth)
        ("AWS_BEARER_TOKEN_BEDROCK", creds.bearer_token),
        # Claude Code auth (IAM-style credentials)
        ("AWS_ACCESS_KEY_ID", creds.access_key),
        ("AWS_SECRET_ACCESS_KEY", creds.secret_key),
        # ALiCE-specific credential vars
        ("BEDROCK_ACCESS_KEY", creds.access_key),
        ("BEDROCK_SECRET_KEY", creds.secret_key),
        # Core Bedrock config
        ("AWS_REGION", creds.region),
        ("CLAUDE_CODE_USE_BEDROCK", _CLAUDE_CODE_USE_BEDROCK),
        ("ANTHROPIC_MODEL", resolve_model_id(DEFAULT_MODEL_ALIAS, arns)),
    ]
    # Claude Code inference profile defaults — resolved to user's ARNs
    for env_var, (alias, _fallback) in CLAUDE_DEFAULT_MODELS.items():
        vars_.append((env_var, resolve_model_id(alias, arns)))

    if fmt is OutputFormat.EXPORT:
        lines: list[str] = [f"# ALiCE credentials for {username} ({session_name})"]
        for key, value in vars_:
            lines.append(f'export {key}="{value}"')
        return "\n".join(lines) + "\n"

    if fmt is OutputFormat.EVAL:
        lines = [f'export {key}="{value}"' for key, value in vars_]
        return "\n".join(lines) + "\n"

    # DOTENV
    lines = [f"{key}={value}" for key, value in vars_]
    return "\n".join(lines) + "\n"
