"""`acdc config` — discover environments, studies, and resolved settings.

These commands turn deploy_config.yaml into a browsable, editable surface so a
new engineer can answer "what environments exist?" and "what will this actually
do?" — and change a setting safely — without reading code or hand-editing YAML.
"""
from __future__ import annotations

import typer

from acdc_aws_etl_pipeline import config
from acdc_aws_etl_pipeline.cli._internal.resolve import env_of, load_cfg, study_of

app = typer.Typer(no_args_is_help=True, help="Inspect and edit deploy_config.yaml.")


@app.command()
def envs() -> None:
    """List the available environment profiles."""
    cfg = load_cfg()
    for name in config.list_envs(cfg):
        typer.echo(name)


@app.command()
def studies() -> None:
    """List the available studies (bare names; env is supplied separately)."""
    cfg = load_cfg()
    for name in config.list_studies(cfg):
        typer.echo(name)


@app.command()
def show(
    env: str = typer.Option(..., "--env", "-e", help="Environment profile."),
    study: str = typer.Option(
        None, "--study", "-s", help="Optional study to resolve against the env."
    ),
) -> None:
    """Print fully-resolved settings for an env (and optionally a study).

    Use this before any upload to confirm the exact AWS profile, secret, and S3
    path that will be used — the staging-vs-prod safety check.
    """
    cfg = load_cfg()
    e = env_of(cfg, env)
    typer.secho(f"Environment: {e.name}", bold=True)
    typer.echo(f"  is_ec2             : {e.is_ec2}")
    typer.echo(f"  region             : {e.region}")
    typer.echo(f"  aws_profile        : {e.aws_profile}")
    typer.echo(f"  aws_secret_name    : {e.aws_secret_name}")
    typer.echo(f"  dictionary_version : {e.dictionary_version}")
    # The resolved URL, not the three raw parts: this is the pre-deploy question
    # ("what will `dict deploy` actually fetch?") and it now spans three config
    # layers, so showing the composed result verifies the resolution itself.
    typer.echo(f"  dictionary_url     : {config.dictionary_url(e)}")
    typer.echo(f"  schema_s3_uri      : {e.schema_s3_uri}")
    typer.echo(f"  domain             : {e.domain}")
    typer.echo(f"  app_name           : {e.app_name}")
    typer.echo(f"  namespace          : {e.namespace}")
    typer.echo(f"  cluster_name       : {e.cluster_name}")
    typer.echo(f"  eks_arn            : {e.eks_arn}")
    typer.echo(f"  ec2_instance_id    : {e.ec2_instance_id}")
    if study:
        s = study_of(cfg, study, env)
        typer.secho(f"Study: {study} -> {s.key}", bold=True)
        typer.echo(f"  project_id       : {s.project_id}")
        typer.echo(f"  program_id       : {s.program_id}")
        typer.echo(f"  s3_metadata_path : {s.s3_metadata_path}")


@app.command("set")
def set_value(
    env: str = typer.Option(..., "--env", "-e", help="Environment profile."),
    key: str = typer.Argument(..., help="Env key to set, e.g. dictionary_version."),
    value: str = typer.Argument(..., help="New value, e.g. v1.1.7."),
) -> None:
    """Set one environment setting and write it back to deploy_config.yaml.

    Example: `acdc config set -e test dictionary_version v1.1.7` — then
    `acdc dict deploy -e test` deploys that version. Comments and formatting
    in the YAML are preserved. Run `acdc config show -e <env>` to confirm.
    """
    try:
        old, new = config.set_env_value(env, key, value)
    except config.ConfigError as exc:
        typer.secho(str(exc), fg=typer.colors.RED, err=True)
        raise typer.Exit(1)
    typer.secho(f"Updated {env}.{key}: {old} -> {new}", fg=typer.colors.GREEN)
