import os
import shutil
import subprocess
import requests

def parse_versions(file_path):
    versions = []
    with open(file_path, 'r') as file:
        for line in file:
            parts = line.strip().split('#')
            version_description = parts[1]
            versions.append(version_description)
    return versions

def download_latest_jar(repo_url, jar_directory, jar_name="ResourcePackConverter.jar"):
    api_url = f"https://api.github.com/repos/{repo_url}/releases"
    response = requests.get(api_url)
    response.raise_for_status()
    releases = response.json()

    jar_url = None
    for release in releases:
        if release['assets']:
            for asset in release['assets']:
                if asset['name'] == jar_name:
                    jar_url = asset['browser_download_url']
                    break
        if jar_url:
            break

    if not jar_url:
        raise FileNotFoundError(f"No JAR file named {jar_name} found in the releases.")

    jar_path = os.path.join(jar_directory, jar_name)

    os.makedirs(jar_directory, exist_ok=True)
    response = requests.get(jar_url)
    response.raise_for_status()

    with open(jar_path, 'wb') as file:
        file.write(response.content)

    return jar_path

def copy_zip_file(src, dst):
    if not os.path.exists(dst):
        os.makedirs(dst)
    shutil.copy(src, dst)

def run_java_command(version, jar_file, input_zip):
    command = f"java -jar {jar_file} --from 1.20 --to {version} -i {input_zip}"
    print(f"Executing: {command}")
    subprocess.run(command, shell=True)

def main(version_type):
    if version_type not in ['v2', 'v3']:
        raise ValueError("Invalid version type. Choose 'v2' or 'v3'.")

    versions_file = f'versions_{version_type}.txt'
    jar_directory = '../Tools/'
    jar_name = "ResourcePackConverter.jar"
    src_zip = f'Examples-{version_type}/VPExample.zip'
    output_dir = f'../../ResourcePacks/Examples-{version_type}/'
    repo_url = "agentdid127/ResourcePackConverter"
    output_zip_name = "VPExample_converted.zip"

    # Remove all zip files in the output directory
    for file in os.listdir(output_dir):
        if file.endswith(".zip"):
            os.remove(os.path.join(output_dir, file))

    # Parse versions from the file
    versions = parse_versions(versions_file)

    # Download the latest JAR file from GitHub
    latest_jar = os.path.join(jar_directory, jar_name)
    # TODO Re-enable
    # latest_jar = download_latest_jar(repo_url, jar_directory, jar_name)

    # Copy the zip file to the tools directory
    copy_zip_file(src_zip, jar_directory)

    try:
        for version_description in versions:
            # Run the Java command
            run_java_command(version_description.split('-')[-1], latest_jar, jar_directory)

            # Define the destination path with the new name
            final_output_path = os.path.join(output_dir, f"VPExample-{version_type}-{version_description}.zip")

            # Move and rename the output zip file to the destination
            output_zip_path = os.path.join(jar_directory, output_zip_name)
            shutil.move(output_zip_path, final_output_path)
            print(f"Moved {output_zip_path} to {final_output_path}")

            # Add the file to git
            os.system(f"git add {final_output_path}")
    finally:
        # Remove the JAR file and the input zip file
        run_path_folder = os.path.join(jar_directory, "VPExample_converted")
        if os.path.exists(run_path_folder):
            shutil.rmtree(run_path_folder)
        # if os.path.exists(latest_jar):
        #     os.remove(latest_jar)
        input_zip_path = os.path.join(jar_directory, os.path.basename(src_zip))
        if os.path.exists(input_zip_path):
            os.remove(input_zip_path)

    print("Conversion completed.")

if __name__ == '__main__':
    import sys
    if len(sys.argv) != 2:
        print("Usage: python convert_versions.py [v2|v3]")
        sys.exit(1)

    version_type = sys.argv[1]
    main(version_type)
