import pathlib
import typing as t

import click

import mantik.cli.runs._arguments as _arguments
import mantik.cli.runs._options as _options
import mantik.cli.runs.runs as runs
import mantik.unicore as unicore


@runs.cli.command("download")
@_arguments.JOB_ID
@_options.API_URL
@_options.BACKEND_CONFIG_ABSOLUTE
@click.option(
    "--remote-path",
    type=click.Path(path_type=pathlib.Path),
    required=False,
    default=None,
    help="""Path of file or subdir in working directory.

        If not defined the whole working directory is downloaded.
    """,
)
@click.option(
    "--local-path",
    type=click.Path(writable=True, path_type=pathlib.Path),
    default=".",
    required=False,
    show_default=True,
    help="Path to output file or directory",
)
def download_file_or_directory(
    job_id: str,
    api_url: t.Optional[str],
    backend_config: t.Optional[pathlib.Path],
    remote_path: t.Optional[pathlib.Path],
    local_path: t.Optional[pathlib.Path],
) -> None:
    """Download a file or folder from a run's working directory.

    JOB_ID is the job ID assigned by UNICORE.

    """

    client = unicore.client.Client.from_api_url_or_config(
        api_url=api_url, config=backend_config
    )
    job = client.get_job(job_id)
    if remote_path is None:
        click.echo(f"Downloading job working directory to {local_path}")
        job.download_all(
            local_path=local_path,
        )
    else:
        click.echo(f"Downloading {remote_path} to {local_path}")
        job.download(
            remote_path=remote_path,
            local_path=local_path,
        )
