import urllib.request
import json
import zipfile
import os
import ssl
import shutil

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = "https://api.github.com/repos/ggerganov/llama.cpp/releases/latest"
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
try:
    with urllib.request.urlopen(req, context=ctx) as response:
        data = json.loads(response.read().decode())

    download_url = None
    for asset in data['assets']:
        if "bin-win-cuda-12.4-x64.zip" in asset['name'] and "cudart" not in asset['name']:
            download_url = asset['browser_download_url']
            break
            
    if download_url:
        print(f"Downloading true binaries: {download_url}...")
        zip_path = "llama_main.zip"
        with urllib.request.urlopen(download_url, context=ctx) as resp, open(zip_path, 'wb') as out_file:
            out_file.write(resp.read())
            
        print("Extracting to temporary folder 'llama_temp'...")
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall("llama_temp")
            
        print("Moving exact files to 'llama_bin_run'...")
        os.makedirs("llama_bin_run", exist_ok=True)
        for root, dirs, files in os.walk("llama_temp"):
            for file in files:
                shutil.move(os.path.join(root, file), os.path.join("llama_bin_run", file))
                
        if os.path.exists("llama_bin"):
            for item in os.listdir("llama_bin"):
                src = os.path.join("llama_bin", item)
                dst = os.path.join("llama_bin_run", item)
                if not os.path.exists(dst):
                    try:
                        shutil.copy(src, dst)
                    except:
                        pass
                        
        os.remove(zip_path)
        shutil.rmtree("llama_temp", ignore_errors=True)
        print("Download and path extraction fully complete.")
    else:
        print("Could not find the target zip.")
except Exception as e:
    print(f"Error: {e}")
