import os
import subprocess
import sys
import shutil

PYTHON_EXE = "D:/Local/dev/python/Python38-32/python.exe"

def build():
    print(f"Starting GUI build using {PYTHON_EXE}")
    
    # Define command
    cmd = [
        PYTHON_EXE,
        "-m", "PyInstaller",
        "--onefile",
        "--noconsole",                  # Start in GUI mode (no console window)
        "--name", "rateloader-gui",
        "--add-data", "settings.ini;.",
        "--add-data", "gui;gui",        # Include gui module
        "--add-data", "core;core",
        "--add-data", "features;features",
        "--add-data", "logo.ico;.",
        "--icon", "logo.ico",
        "--hidden-import", "cx_Oracle",
        "--hidden-import", "requests",
        "--hidden-import", "dateutil",
        "--hidden-import", "configparser",
        "--hidden-import", "logging.handlers",
        "--hidden-import", "tkinter",
        "--collect-all", "cx_Oracle",
        "--collect-all", "requests",
        "--collect-all", "dateutil",
        "gui/app.py"                    # GUI entry point
    ]
    
    print("Executing command:", " ".join(cmd))
    
    try:
        # Clean previous
        if os.path.exists("build"): shutil.rmtree("build")
        if os.path.exists("dist"): shutil.rmtree("dist")
        
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        print("Success!")
        # print(result.stdout) # Output can be very long
        
        if os.path.exists("dist/rateloader-gui.exe"):
            print(f"EXE created at dist/rateloader-gui.exe")
            return True
    except subprocess.CalledProcessError as e:
        print("Build failed")
        print(e.stderr)
        return False
    except Exception as e:
        print(f"An error occurred: {e}")
        return False

if __name__ == "__main__":
    build()
