import sys
import os
import subprocess
import shutil
import platform

def clean_build_dirs():
    """Removes build and dist directories if they exist."""
    for d in ["build", "dist"]:
        if os.path.exists(d):
            print(f"Cleaning {d}...")
            shutil.rmtree(d)
    
    spec_file = "TeletextEditor_Linux.spec" if platform.system() == "Linux" else "TeletextEditor_Windows.spec"
    if os.path.exists(spec_file):
        os.remove(spec_file)

def build():
    system = platform.system()
    print(f"Detected OS: {system}")

    # Determine separator for --add-data
    sep = ";" if system == "Windows" else ":"
    
    # Base command
    base_cmd = [
        sys.executable, "-m", "PyInstaller",
        "--onefile",
        "--windowed",
        "--hidden-import=pkgutil",
        "--hidden-import=PyQt6.sip",
        "--collect-all", "PyQt6",
        "--paths", "src",
        f"--add-data=app_icon.png{sep}.",
        "src/main.py"
    ]

    if system == "Linux":
        name = "TeletextEditor_Linux"
    elif system == "Windows":
        name = "TeletextEditor_Windows.exe"
        # Add icon for Windows executable
        base_cmd.append("--icon=app_icon.ico")
    else:
        print(f"Unsupported platform: {system}")
        return

    cmd = base_cmd + ["--name", name]

    print("Running build command:")
    print(" ".join(cmd))

    try:
        subprocess.check_call(cmd)
        print("\n" + "="*40)
        print(f"Build successful! Executable is in 'dist/{name}'")
        print("="*40)
    except subprocess.CalledProcessError as e:
        print(f"Build failed with error code {e.returncode}")
        sys.exit(1)

    # Cross-compilation note
    if system == "Linux":
        print("\nNote: To build the Windows executable, please run this script on Windows.")
    elif system == "Windows":
        print("\nNote: To build the Linux executable, please run this script on Linux.")

if __name__ == "__main__":
    clean_build_dirs()
    build()