#!/usr/bin/env python3

import os, sys, argparse, tempfile, subprocess, shutil, requests
from git.repo import Repo
from termcolor import cprint

parser = argparse.ArgumentParser(description="a helper script for liightninggod modpacks")

parser.add_argument("--export", "-e", help="export modpack zip", action="store_true")
parser.add_argument("--release", "-r", help="release modpack version", action="store_true")
parser.add_argument("--setup", "-s", help="setup project and install dependencies", action="store_true")
parser.add_argument("--force", "-f", help="forces things when needed, like redoing setup", action="store_true")
parser.add_argument("--build-pax", help="builds pax from source, even if on a supported platform", action="store_true")
args = parser.parse_args()

WORKING_DIR = os.getcwd()

PAX_GITHUB = "https://github.com/froehlichA/pax"
PAX_LATEST_RELEASE = f"{PAX_GITHUB}/releases/latest/download"
PAX_LINUX = f"{PAX_LATEST_RELEASE}/pax"
PAX_WINDOWS = f"{PAX_LATEST_RELEASE}/pax-windows.zip"

MODPACK_GIT = "https://git.233hfd.com/joey/FishPogPixelmon"
MODPACK_RELEASES_URL = "https://git.233hfd.com/api/v1/repos/joey/FishPogPixelmon/releases"


OS = sys.platform


def __main__():
    if args.setup:
        print("setting up tooling")
        setup_pack()
        return
    elif args.export:
        print("exporting modpack")
        export_pack()
        return
    elif args.release:
        release()
        return

    print(
        "no command provided. pass the -h flag to see commands for tooling, or run ./pax to interact with the modpack's files"
    )


# setup
def setup_pack():
    pax()


# release
def release():
    print("releasing modpack")

    if not command_exists("tea"):
        cprint("gitea cli is not installed - make sure it is installed for your platform", "red")
        exit(1)

    repo = Repo(WORKING_DIR)
    if repo.is_dirty():
        cprint("repo is dirty - commit changes before releasing", "red")
        exit(1)

    export_pack()

    print("enter the version number for this release")
    print(f"the last release was: {most_recent_release()}")
    version = input("version: v")

    subprocess.run(
        [
            "tea",
            "release",
            "create",
            "-t",
            f"v{version}",
            "-a",
            ".out/FishPogPixelmon.zip",
            f"v{version}",
        ]
    )


# export
def export_pack():
    subprocess.run(["./pax", "export"])
    os.rename(".out/FishPog Pixelmon.zip", ".out/FishPogPixelmon.zip")


# pax
def pax():
    if os.path.isfile(os.path.join(WORKING_DIR, "pax")) and not args.force:
        print("pax is already installed")
        return

    if OS == "darwin" or args.build_pax:
        print("building pax from source...")
        pax_from_source()
        print("pax built successfully")
        return

    if OS == "linux":
        print("downloading pax binary for linux...")
        r = requests.get(PAX_LINUX, allow_redirects=True)
        open("pax", "wb").write(r.content)
        os.chmod("pax", 0o755)
        return

    if OS == "windows":
        print("downloading and extracting pax for windows...")
        r = requests.get(PAX_WINDOWS, allow_redirects=True)
        open("pax-windows.zip", "wb").write(r.content)
        shutil.unpack_archive("pax-windows.zip", ".")
        os.remove("pax-windows.zip")
        return


def pax_from_source():
    if OS == "windows":
        cprint("building from source not supported on windows yet", "red")
        exit(1)

    if not command_exists("nimble"):
        cprint("nim is not installed - make sure it is installed for your platform", "red")
        exit(1)

    TMP = tempfile.mkdtemp()
    os.chdir(TMP)

    subprocess.run(["git", "clone", PAX_GITHUB], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    os.chdir("pax")

    subprocess.run(["nimble", "build", "-y", "-d:release"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    subprocess.run(["cp", "pax", WORKING_DIR])


# git
def most_recent_release() -> str:
    r = requests.get(MODPACK_RELEASES_URL)
    releases: list[dict] = r.json()
    if len(releases) == 0:
        return "none"
    return releases[0]["tag_name"]


# helper functions
def command_exists(binary_name):
    return shutil.which(binary_name) is not None


# entry
__main__()
