#!/usr/bin/env python
"""
Script to build the Excel Filter application into a standalone executable using PyInstaller.
"""

import os
import subprocess
import sys

# Define the main script to be converted
MAIN_SCRIPT = "gui_new.py"

# Define the output directory for the executable
OUTPUT_DIR = "dist"

# Define the name of the executable
EXECUTABLE_NAME = "ExcelFilter"

# Define additional files to include (e.g., icons, scripts, etc.)
# Note: config.json and presets.json are no longer included as they are now stored
# in the user's data directory (AppData on Windows) to avoid permission issues
ADDITIONAL_FILES = [
    ("app_icon.ico", "."),
    ("check_python.py", "."),
    ("check_environment.bat", "."),
    ("LICENSE.txt", "."),
    ("locales", "locales"),
]

# Define hidden imports (if any)
HIDDEN_IMPORTS = [
    "openpyxl",
    "pandas.io.excel._openpyxl",
    "pandas.io.excel._base",
    "pandas.io.common",
    "tkinter",
    "tkinter.filedialog",
    "tkinter.messagebox",
    "tkinter.ttk"
]

# Define excluded modules (if any)
EXCLUDED_MODULES = []

# Define the PyInstaller command
pyinstaller_command = [
    "pyinstaller",
    "--onefile",  # Create a single executable file
    "--windowed",  # Prevent console from showing (for GUI applications)
    f"--name={EXECUTABLE_NAME}",  # Name of the executable
    f"--distpath={OUTPUT_DIR}",  # Output directory
    "--icon=app_icon.ico",  # Set the icon for the executable
    MAIN_SCRIPT,  # Main script to convert
]

# Add the additional files using the --add-data option
for src, dest in ADDITIONAL_FILES:
    pyinstaller_command.append(f"--add-data={src};{dest}")

# Add hidden imports
for hidden_import in HIDDEN_IMPORTS:
    pyinstaller_command.append(f"--hidden-import={hidden_import}")

# Filter out empty strings from the command
pyinstaller_command = [cmd for cmd in pyinstaller_command if cmd]

# Run the PyInstaller command
print("Building the executable...")
print("Command:", " ".join(pyinstaller_command))

try:
    # Use python -m PyInstaller to ensure PyInstaller is found
    pyinstaller_full_command = [sys.executable, "-m", "PyInstaller"] + pyinstaller_command[1:]
    print("Full command:", " ".join(pyinstaller_full_command))
    subprocess.run(pyinstaller_full_command, check=True)
    print("Executable built successfully!")
except subprocess.CalledProcessError as e:
    print(f"Error building the executable: {e}")
    sys.exit(1)
except Exception as e:
    print(f"An unexpected error occurred: {e}")
    sys.exit(1)

# Clean up the build directory (optional)
def cleanup_build_directory():
    """Attempt to clean up the build directory with multiple strategies"""
    if os.path.exists("build"):
        import shutil
        import time
        import stat
        
        # Try multiple cleanup strategies
        for attempt in range(3):
            try:
                # First, try to make files writable
                for root, dirs, files in os.walk("build"):
                    for d in dirs:
                        try:
                            os.chmod(os.path.join(root, d), stat.S_IWRITE)
                        except:
                            pass
                    for f in files:
                        try:
                            os.chmod(os.path.join(root, f), stat.S_IWRITE)
                        except:
                            pass
                
                # Now try to remove the directory
                shutil.rmtree("build")
                print("Build directory cleaned up.")
                return True
            except Exception as e:
                if attempt < 2:  # Don't wait on last attempt
                    time.sleep(1)  # Wait a bit and try again
                else:
                    print(f"Warning: Could not clean up build directory: {e}")
                    print("You can manually delete the 'build' directory if needed.")
                    return False
    return True

# Attempt cleanup
cleanup_build_directory()

print("Done!")
