import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Tuple, Union

from clarabot_nano.utility.dirs import Directories
from dev_tools.utility.path import ROOT

GIT_VERSION_RE = re.compile(r"^v([^-]+)(.*)\n$")


def dev_cache_dir():
    ds = Directories.instance()
    cache_dir = ds.get_user_app_data_dir("devtest", "cache")
    cache_dir.mkdir(parents=True, exist_ok=True)
    return cache_dir


def dev_build_dir():
    ds = Directories.instance()
    cache_dir = ds.get_user_app_data_dir("devtest", "build")
    cache_dir.mkdir(parents=True, exist_ok=True)
    return cache_dir


def get_build_version_by_git() -> Tuple[str, str]:
    git_describe = subprocess.check_output(
        ["git.exe" if sys.platform.startswith("win") else "git", "describe", "--tags"], cwd=str(ROOT)
    )
    m = GIT_VERSION_RE.match(git_describe.decode())
    assert m, str(git_describe)
    return m.group(1), m.group(2)


def git_archive(output_path: Union[str, Path], git_name: str = "HEAD"):
    return subprocess.check_call(
        [
            "git.exe" if sys.platform.startswith("win") else "git",
            "archive",
            "--format=zip",
            "-9",
            "-o",
            str(output_path),
            git_name,
        ],
        cwd=str(ROOT),
    )


def get_first_file_found(*args: Union[str, Path]) -> str:
    for file in args:
        if isinstance(file, str):
            file = shutil.which(file)
            if file:
                return file
        elif file.is_file():
            return str(file)
        else:
            assert False, f"unsupported type {file}"
    assert False, f"not found any of {args}"
