"""alice list-secrets — List secrets under the current namespace/environment."""

from __future__ import annotations

import json

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_table
from alice_cli.errors import AliceCLIError
from alice_cli.secrets import is_secret_owned_by_user


@click.command("list-secrets")
@click.option("--json", "output_json", is_flag=True, help="Output as JSON to stdout")
@click.pass_context
def list_secrets(ctx: click.Context, output_json: bool) -> None:
    """List secrets in the current namespace."""
    config = ctx.obj["config"]

    print_banner(personality.BANNER, config.quiet)

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

    prefix = f"{config.namespace}/{config.environment}/"
    print_status(f"Listing secrets under: {prefix}", config.quiet)

    session = boto3.Session(profile_name=config.profile, region_name=config.region)
    client = session.client("secretsmanager")

    secrets: list[dict[str, str]] = []
    try:
        paginator = client.get_paginator("list_secrets")
        for page in paginator.paginate(
            Filters=[{"Key": "name", "Values": [prefix]}],
        ):
            for secret in page.get("SecretList", []):
                name = secret.get("Name", "")

                # Filter out other users' bedrock-api-keys
                if not is_secret_owned_by_user(name, username_result.username):
                    continue

                last_changed = secret.get("LastChangedDate", "")
                # Format datetime if present
                if hasattr(last_changed, "strftime"):
                    last_changed = last_changed.strftime("%Y-%m-%d %H:%M:%S")
                else:
                    last_changed = str(last_changed)
                secrets.append({"name": name, "last_changed": last_changed})
    except ClientError as exc:
        raise AliceCLIError(f"Secrets Manager error: {exc}") from exc

    if output_json:
        click.echo(json.dumps(secrets, indent=2))
        return

    rows = [[s["name"], s["last_changed"]] for s in secrets]

    print_table(
        title=f"Secrets under {prefix}",
        columns=["Name", "Last Changed"],
        rows=rows,
    )
