from __future__ import annotations

import shutil
from pathlib import Path

import click
from dopt_basics import io

from pycage.helpers import (
    delete_folder_recursively,
    get_interpreter,
    print_error,
)


@click.command(help="copy created python standalone folder to other location")
@click.argument(
    "dest",
    type=click.Path(
        dir_okay=True,
        writable=True,
        path_type=Path,
    ),
)
@click.option("-f", "--force", is_flag=True, default=False, show_default=True)
def copy(
    dest: Path,
    force: bool,
) -> None:
    try:
        pth_intp = get_interpreter()
    except RuntimeError:
        click.echo("Base interpreter path could not be found", err=True)
        return

    if not dest.is_absolute():
        dest = (Path.cwd() / dest).resolve()

    dest = io.prepare_path(dest, ("python",), None, None)
    if dest.exists() and not force:
        click.echo(
            "Path already exists. If you wish to delete and "
            "copy the folder, use the flag ``--force``"
        )
        return

    src = pth_intp.parent

    try:
        delete_folder_recursively(dest)
        shutil.copytree(src, dest, dirs_exist_ok=True)
    except Exception as err:
        print_error(err)
