from __future__ import annotations

import os
import shutil
import stat
from pathlib import Path

import click

from pycage import config, helpers


def print_error(
    error: Exception,
) -> None:
    click.echo(f"During the procedure the following exception occurred: {error}", err=True)


def path_verify_existence(path: Path) -> None:
    if not path.exists():
        raise FileNotFoundError(f"Path does not exist: >{path}<")


def path_verify_directory(path: Path) -> None:
    if not path.is_dir():
        raise ValueError(f"Path is not a directory: >{path}<")


def delete_folder_recursively(
    folder: Path,
    verbose: bool = False,
) -> None:
    if not folder.exists():
        return

    if verbose:
        print(
            f"Target folder with name >{folder.name}< already exists and "
            "is deleted automatically."
        )

    path_verify_directory(folder)
    if not folder.is_absolute():
        folder = folder.absolute()

    if not os.access(folder, os.W_OK):
        os.chmod(folder, stat.S_IWUSR)
    shutil.rmtree(folder)


def get_interpreter() -> Path:
    exec_interp = config.CFG.os_info.INTERPRETER
    pth_int = Path.cwd() / "python" / exec_interp
    try:
        helpers.path_verify_existence(pth_int)
    except FileNotFoundError as err:
        raise RuntimeError("Base interpreter not found") from err

    return pth_int
