"""`acdc metadata` — upload real study metadata to Gen3 (data-plane).

These are the multi-hour jobs, so they support ``--on ec2`` to run on the EC2
box via SSM (disconnect-safe) instead of the laptop.
"""
from __future__ import annotations

import typer

from acdc_aws_etl_pipeline.cli._internal import dispatch
from acdc_aws_etl_pipeline.cli._internal.dispatch import DispatchMech, Target
from acdc_aws_etl_pipeline.cli._internal.resolve import load_cfg, study_of

app = typer.Typer(no_args_is_help=True, help="Upload study metadata to Gen3.")

_UPLOAD = "services/upload/metadata/upload_metadata.py"
_UPLOAD_ALL = "services/upload/metadata/upload_all_studies.sh"


@app.command()
def upload(
    study: str = typer.Option(..., "--study", "-s", help="Study, e.g. ausdiab."),
    env: str = typer.Option(..., "--env", "-e", help="Environment profile."),
    node: str = typer.Option(None, "--node", help="Submit only this node type."),
    on: Target = typer.Option(Target.local, "--on", help="Run local or on ec2."),
    dispatch_mech: DispatchMech = typer.Option(
        DispatchMech.ssm, "--dispatch", help="EC2 dispatch mechanism."
    ),
    key: str = typer.Option(None, "--key", help="SSH key (for --dispatch ssh)."),
) -> None:
    """Upload a study's release metadata to Gen3 sheepdog.

    Examples:
      acdc metadata upload --study ausdiab --env staging
      acdc metadata upload --study ausdiab --env staging --on ec2
    """
    cfg = load_cfg()
    s = study_of(cfg, study, env)

    def build_args(env_name):
        a = ["--study", s.key, "--env", env_name]
        if node:
            a += ["--specific-node", node]
        return a

    dispatch.run_or_dispatch(
        on, cfg, env, _UPLOAD, build_args, "metadata-upload",
        mech=dispatch_mech, ssh_key=key,
    )


@app.command(name="upload-all")
def upload_all(
    studies: str = typer.Option(
        ..., "--studies", help="Comma-separated studies, e.g. ausdiab,caughtcad."
    ),
    env: str = typer.Option(..., "--env", "-e", help="Environment profile."),
    on: Target = typer.Option(Target.local, "--on", help="Run local or on ec2."),
    dispatch_mech: DispatchMech = typer.Option(
        DispatchMech.ssm, "--dispatch", help="EC2 dispatch mechanism."
    ),
    key: str = typer.Option(None, "--key", help="SSH key (for --dispatch ssh)."),
) -> None:
    """Upload several studies sequentially (wraps upload_all_studies.sh).

    The wrapped script aborts on any 'prod' environment.
    """
    cfg = load_cfg()
    names = [s.strip() for s in studies.split(",") if s.strip()]
    keys = [study_of(cfg, name, env).key for name in names]

    def build_args(env_name):
        return ["--studies", ",".join(keys), "--env", env_name]

    dispatch.run_or_dispatch(
        on, cfg, env, _UPLOAD_ALL, build_args, "metadata-upload-all",
        interpreter="bash", mech=dispatch_mech, ssh_key=key,
    )
