"""alice config — Show resolved configuration and value sources."""

from __future__ import annotations

import os

import click

from alice_cli.console import print_table
from alice_cli.teaparty.audio_locker import resolve_audio_bucket


def _get_source(param_name: str, parent_ctx: click.Context) -> str:
    """Determine the source of a CLI parameter value.

    Checks the Click parameter source on the parent (cli group) context.
    For --namespace and --environment, if Click reports DEFAULT but the
    corresponding env var is set, the actual source is the env var (since
    resolve_config applies the env-var fallback internally).
    """
    source = parent_ctx.get_parameter_source(param_name)

    if source == click.core.ParameterSource.COMMANDLINE:
        return "CLI flag"
    if source == click.core.ParameterSource.ENVIRONMENT:
        return "env var"

    # source is DEFAULT — but resolve_config may have used an env var
    env_map: dict[str, str] = {
        "namespace": "ALICE_NAMESPACE",
        "environment": "ALICE_ENVIRONMENT",
        "profile": "AWS_PROFILE",
    }
    env_var = env_map.get(param_name)
    if env_var and os.environ.get(env_var):
        return "env var"

    return "default"


@click.command("config")
@click.pass_context
def config_cmd(ctx: click.Context) -> None:
    """View current configuration and where values come from."""
    config = ctx.obj["config"]
    parent_ctx = ctx.parent
    assert parent_ctx is not None, "config command must be invoked as a subcommand"

    rows: list[list[str]] = [
        ["profile", str(config.profile or ""), _get_source("profile", parent_ctx)],
        ["region", config.region, _get_source("region", parent_ctx)],
        ["namespace", config.namespace, _get_source("namespace", parent_ctx)],
        ["environment", config.environment, _get_source("environment", parent_ctx)],
        ["quiet", str(config.quiet), _get_source("quiet", parent_ctx)],
        ["audio_bucket", resolve_audio_bucket(config), "resolved"],
    ]

    print_table(
        title="ALiCE Configuration",
        columns=["Setting", "Value", "Source"],
        rows=rows,
    )
