"""`acdc dict` — data dictionary operations (pull / upload / deploy).

All local: dictionary deploy restarts Gen3 schema microservices via the ArgoCD
SSO browser flow, which only works interactively on the laptop.
"""
from __future__ import annotations

import typer

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

app = typer.Typer(no_args_is_help=True, help="Data dictionary operations (local).")


def _version(env_cfg, override):
    return override or env_cfg.dictionary_version


@app.command()
def pull(
    env: str = typer.Option(..., "--env", "-e", help="Environment profile."),
    version: str = typer.Option(
        None, "--version", help="Dictionary git tag (default: from config)."
    ),
) -> None:
    """Download the dictionary JSON for the env's version.

    The source location comes from `common.dictionary` in deploy_config.yaml (or
    the env's own `dictionary_*` overrides), so pointing at a different schema
    repo is a config edit, not a code change.

    Examples:
      acdc dict pull --env test
      acdc dict pull --env staging --version v1.1.5
    """
    cfg = load_cfg()
    e = env_of(cfg, env)
    v = _version(e, version)
    runner.run(
        runner.bash_script(
            "services/dictionary/pull_dict.sh",
            config.dictionary_url(e, v),
            config.dictionary_filename(e, v),
        )
    )


@app.command()
def upload(
    env: str = typer.Option(..., "--env", "-e", help="Environment profile."),
    version: str = typer.Option(
        None, "--version", help="Dictionary git tag (default: from config)."
    ),
) -> None:
    """Upload the (already pulled) dictionary JSON to the env's S3 location."""
    cfg = load_cfg()
    e = env_of(cfg, env)
    v = _version(e, version)
    local_file = config.dictionary_local_relpath(e, v)
    s3_uri = f"s3://{e.schema_s3_uri}"
    args = [local_file, s3_uri]
    if e.aws_profile:
        args.append(e.aws_profile)
    runner.run(runner.python_script("services/dictionary/upload_dictionary.py", *args))


@app.command()
def deploy(
    env: str = typer.Option(..., "--env", "-e", help="Environment profile."),
) -> None:
    """Pull + upload the dictionary and restart Gen3 schema microservices.

    Wraps services/dictionary/deploy_dd.sh. Requires an interactive ArgoCD SSO
    login, so it runs locally only.

    The deployed version comes from the env's `dictionary_version` in
    deploy_config.yaml; change it first with
    `acdc config set -e <env> dictionary_version <tag>`.

    Examples:
      acdc dict deploy --env test
    """
    cfg = load_cfg()
    env_of(cfg, env)  # validate early with a friendly error
    runner.run(runner.bash_script("services/dictionary/deploy_dd.sh", env))
