"""`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.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).")

_DICT_URL_TMPL = (
    "https://raw.githubusercontent.com/AustralianBioCommons/acdc-schema-json/"
    "refs/tags/{version}/dictionary/prod_dict/acdc_schema.json"
)


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 from GitHub for the env's version.

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


@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 = f"services/dictionary/schemas/acdc_schema_{v}.json"
    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))
