"""alice status — Check SSO session, identity, and connectivity."""

from __future__ import annotations

import json

import click

from alice_cli import __version__, personality
from alice_cli.auth import detect_identity_from_key, detect_username
from alice_cli.console import print_banner, print_status, print_table, spinner
from alice_cli.errors import AuthError


@click.command("status")
@click.option("--json", "output_json", is_flag=True, help="Output as JSON to stdout")
@click.pass_context
def status(ctx: click.Context, output_json: bool) -> None:
    """Check SSO session and AWS connectivity."""
    config = ctx.obj["config"]

    print_banner(personality.BANNER, config.quiet)

    data: dict[str, str] = {"version": __version__}

    with spinner(personality.status_checking_session(), config.quiet):
        try:
            result = detect_username(config.profile, config.region)
            data["jhed"] = result.username
            data["session"] = result.session_name
            data["account"] = result.arn.split(":")[4]
        except AuthError:
            if config.bedrock_secret_key and not config.profile:
                identity = detect_identity_from_key(config.bedrock_access_key)
                data["auth"] = "API key mode (SSO bypassed)"
                if identity and identity != "unknown":
                    data["identity"] = identity
            else:
                print_status(
                    "SSO session is not active. Run: aws sso login",
                    config.quiet,
                )

    data["region"] = config.region
    data["namespace"] = config.namespace
    data["environment"] = config.environment

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

    rows = [[k.capitalize(), v] for k, v in data.items()]
    print_table(title="ALiCE Status", columns=["Setting", "Value"], rows=rows)
