"""`acdc indexd` — register S3 files with Gen3 indexd (data-plane).

Interactive op the author runs on EC2, so it supports ``--on ec2``.
"""
from __future__ import annotations

from typing import List

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="Register files with Gen3 indexd.")

_REGISTER = "services/indexd/register_indexd.py"


@app.command()
def register(
    s3_paths: List[str] = typer.Option(
        ..., "--s3-paths", help="One or more S3 prefixes to scan (repeatable)."
    ),
    study: str = typer.Option(..., "--study", "-s", help="Study, e.g. edcad."),
    env: str = typer.Option(..., "--env", "-e", help="Environment profile."),
    dry_run: bool = typer.Option(
        False, "--dry-run", help="Scan + write file_metadata only; skip indexd."
    ),
    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:
    """Scan S3 prefixes and register the files with Gen3 indexd.

    Examples:
      acdc indexd register --s3-paths s3://bucket/edcad/ --study edcad --env staging
      acdc indexd register --s3-paths s3://b/a/ --s3-paths s3://b/c/ --study edcad --env staging --on ec2
    """
    cfg = load_cfg()
    s = study_of(cfg, study, env)

    def build_args(env_name):
        a = ["--s3-paths", *s3_paths, "--study", s.key, "--env", env_name]
        if dry_run:
            a.append("--dry-run")
        return a

    dispatch.run_or_dispatch(
        on, cfg, env, _REGISTER, build_args, "indexd-register",
        mech=dispatch_mech, ssh_key=key,
    )
