#!/usr/bin/env python3

import os, sys, shutil, requests, tempfile, glob, subprocess
from termcolor import cprint
from typing import Any

OS = sys.platform

MOD_DOWNLOADER_URL = "https://github.com/Advik-B/CMPDL/releases/download/v3.0.0/CMPDL-raw.ZipApp.zip"

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

MULTIMC_DOWNLOAD_URL_WINDOWS = "https://files.multimc.org/downloads/mmc-develop-win32.zip"
MULTIMC_PARENT_DIR = ""
MULTIMC_DIR = ""

if OS == "darwin":
    cprint("no support for macos yet", "red")
    exit(1)

if OS == "linux":
    MULTIMC_PARENT_DIR = f"{os.getenv('HOME')}/.local/share"
    MULTIMC_DIR = f"{MULTIMC_PARENT_DIR}/multimc"

if OS == "windows":
    MULTIMC_PARENT_DIR = f"{os.getenv('APPDATA')}/FishPog"
    MULTIMC_DIR = f"{MULTIMC_PARENT_DIR}/MultiMC"

INSTANCE_DIR = f"{MULTIMC_DIR}/instances/FishPogPixelmon"


# main
def __main__():
    header()
    multimc()
    needs_mods = instance()
    if needs_mods:
        mods()
    run_mmc()


# run
def run_mmc():
    cprint("ready to go! starting multimc!", "green")
    os.chdir(MULTIMC_DIR)

    if OS == "windows":
        subprocess.Popen(["MultiMC.exe"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    if OS == "linux":
        subprocess.Popen(["./MultiMC"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


# mods
def mods():
    os.chdir(INSTANCE_DIR)

    if not os.path.exists(f"{INSTANCE_DIR}/downloader.zip"):
        cprint("downloader.zip not found - downloading", "yellow")
        r = requests.get(MOD_DOWNLOADER_URL, allow_redirects=True)
        open("downloader.zip", "wb").write(r.content)

    cprint("downloading mods. this may take a while, please wait.", "green")
    subprocess.run(["python", "downloader.zip", "manifest.json"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    for file in glob.glob(f"{INSTANCE_DIR}/mods/*"):
        name = os.path.basename(file)
        shutil.move(file, os.path.join(f"{INSTANCE_DIR}/.minecraft/mods", name))

    shutil.rmtree(f"{INSTANCE_DIR}/mods")

    cprint("mods downloaded successfully", "green")


# multimc
def instance():
    unclean = False
    release = most_recent_release()

    if not os.path.exists(INSTANCE_DIR):
        unclean = True
        cprint("instance not found - downloading", "yellow")
        download_instance(release)

    version = ""
    if os.path.exists(f"{INSTANCE_DIR}/.version"):
        f = open(f"{INSTANCE_DIR}/.version", "r")
        version = f.read()

    if version != release["tag_name"]:
        unclean = True
        cprint("new update available! - downloading", "green")
        download_instance(release)

    cprint("instance is up to date", "green")
    return unclean


def download_instance(release: dict[str, Any]):
    os.makedirs(f"{INSTANCE_DIR}/.minecraft", exist_ok=True)

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

    download_url = get_release_asset(release)
    r = requests.get(download_url, allow_redirects=True)
    open("instance.zip", "wb").write(r.content)
    shutil.unpack_archive("instance.zip", ".")
    os.remove("instance.zip")

    for file in glob.glob(f"{TMP}/overrides/*"):
        if file == f"{TMP}/overrides/options.txt" and os.path.exists(f"{INSTANCE_DIR}/.minecraft/options.txt"):
            continue
        name = os.path.basename(file)
        shutil.move(file, os.path.join(f"{INSTANCE_DIR}/.minecraft", name))

    shutil.rmtree(f"{TMP}/overrides")

    for file in glob.glob(f"{TMP}/*"):
        name = os.path.basename(file)
        shutil.move(file, os.path.join(INSTANCE_DIR, name))

    shutil.rmtree(TMP)

    os.chdir(INSTANCE_DIR)
    shutil.copy(
        os.path.join(INSTANCE_DIR, "fishpog_pixelmon.png"), os.path.join(MULTIMC_DIR, "icons", "fishpog_pixelmon.png")
    )

    f = open(".version", "w")
    f.write(release["tag_name"])
    f.close()


def multimc():
    if os.path.exists(MULTIMC_DIR):
        return

    if OS != "windows":
        cprint("multimc is not installed - please install it", "red")
        exit(1)

    os.makedirs(MULTIMC_PARENT_DIR, exist_ok=True)
    os.chdir(MULTIMC_PARENT_DIR)

    cprint("multimc is not installed - installing", "yellow")
    r = requests.get(MULTIMC_DOWNLOAD_URL_WINDOWS, allow_redirects=True)
    open("multimc.zip", "wb").write(r.content)
    shutil.unpack_archive("multimc.zip", ".")
    os.remove("multimc.zip")
    return


# releases
def most_recent_release() -> dict[str, Any]:
    r = requests.get(MODPACK_RELEASES_URL)
    releases: list[dict[str, Any]] = r.json()
    return releases[0]


def most_recent_version(release: dict[str, Any]) -> str:
    return release["tag_name"]


def get_release_asset(release: dict[str, Any]):
    return release["assets"][0]["browser_download_url"]


# ascii art lol
def header():
    cprint(
        """
 _______  __         __     _______
|   _   ||__|.-----.|  |--.|   _   |.-----..-----.
|.  1___||  ||__ --||     ||.  1   ||  _  ||  _  |
|.  __)  |__||_____||__|__||.  ____||_____||___  |
|:  |                      |:  |           |_____|
|::.|                      |::.|
`---'                      `---'

 _______  __                __
|   _   ||__|.--.--..-----.|  |.--------..-----..-----.
|.  1   ||  ||_   _||  -__||  ||        ||  _  ||     |
|.  ____||__||__.__||_____||__||__|__|__||_____||__|__|
|:  |
|::.|
`---'
        """,
        "green",
    )


# run app
__main__()
