#!/usr/bin/env python3
"""
Build script for creating rateloader-gui.exe using PyInstaller.

This script creates a standalone Windows executable for the rateloader GUI application
with all dependencies included and proper configuration for runtime paths.
"""

import os
import sys
import subprocess
import shutil

def build_exe():
    """Build the standalone executable using PyInstaller."""
    
    print("Building rateloader-gui.exe...")
    
    # PyInstaller command with all necessary options
    pyinstaller_cmd = [
        sys.executable,
        "-m", "PyInstaller",
        "--onefile",                    # Single executable file
        "--windowed",                   # No console window (GUI app)
        "--name", "rateloader-gui",     # Output name
        "--add-data", "settings.ini;.", # Include settings.ini in root
        "--add-data", "gui;gui",        # Include GUI module
        "--add-data", "core;core",      # Include core module
        "--add-data", "features;features", # Include features module
        "--add-data", "logo.ico;.",     # Include application icon
        "--icon", "logo.ico",           # Set executable icon
        "--hidden-import", "tkinter",   # Explicitly include tkinter
        "--hidden-import", "tkinter.ttk",
        "--hidden-import", "tkinter.messagebox",
        "--hidden-import", "tkinter.filedialog",
        "--hidden-import", "tkinter.scrolledtext",
        "--hidden-import", "cx_Oracle", # Oracle database connector
        "--hidden-import", "smtplib",   # Email functionality
        "--hidden-import", "email.mime.multipart",
        "--hidden-import", "email.mime.text",
        "--hidden-import", "email.mime.base",
        "--hidden-import", "email.encoders",
        "--hidden-import", "requests",  # HTTP requests
        "--hidden-import", "urllib.request",
        "--hidden-import", "urllib.error",
        "--hidden-import", "dateutil",  # Date utilities
        "--hidden-import", "dateutil.relativedelta",
        "--hidden-import", "configparser", # Configuration handling
        "--hidden-import", "logging.handlers", # Rotating file handlers
        "--hidden-import", "concurrent.futures", # Thread pool
        "--hidden-import", "http.server", # HTTP server
        "--hidden-import", "socketserver",
        "--hidden-import", "threading", # Threading
        "--hidden-import", "queue",     # Task queue
        "--hidden-import", "enum",      # Enum support
        "--collect-all", "cx_Oracle",   # Collect all cx_Oracle dependencies
        "--collect-all", "requests",    # Collect all requests dependencies
        "--collect-all", "dateutil",    # Collect all dateutil dependencies
        "gui/app.py"                    # Entry point
    ]
    
    try:
        # Run PyInstaller
        print("Executing PyInstaller command...")
        result = subprocess.run(pyinstaller_cmd, check=True, capture_output=True, text=True)
        print("PyInstaller output:")
        print(result.stdout)
        
        # Check if executable was created
        exe_path = os.path.join("dist", "rateloader-gui.exe")
        if os.path.exists(exe_path):
            print(f"\n✅ Successfully created: {exe_path}")
            print(f"   File size: {os.path.getsize(exe_path) / (1024*1024):.1f} MB")
            
            # Create a simple test to verify the executable
            print("\n📋 Testing executable...")
            try:
                test_result = subprocess.run([exe_path, "--help"], capture_output=True, text=True, timeout=10)
                if test_result.returncode == 0 or "GUI" in test_result.stderr or "tkinter" in test_result.stderr:
                    print("✅ Executable test passed")
                else:
                    print("⚠️  Executable test may have issues (this is normal for GUI apps)")
            except subprocess.TimeoutExpired:
                print("⚠️  Executable test timed out after 10 seconds (expected for GUI apps)")
            
            return True
        else:
            print(f"❌ Executable not found at expected location: {exe_path}")
            return False
            
    except subprocess.CalledProcessError as e:
        print(f"❌ PyInstaller failed with exit code {e.returncode}")
        print("STDOUT:", e.stdout)
        print("STDERR:", e.stderr)
        return False
    except Exception as e:
        print(f"❌ Build failed with error: {str(e)}")
        return False

def clean_build():
    """Clean previous build artifacts."""
    print("Cleaning previous build artifacts...")
    
    dirs_to_clean = ["build", "dist", "__pycache__"]
    for dir_name in dirs_to_clean:
        if os.path.exists(dir_name):
            try:
                shutil.rmtree(dir_name)
                print(f"  Removed {dir_name}/")
            except Exception as e:
                print(f"  Warning: Could not remove {dir_name}/: {str(e)}")
    
    # Clean .spec files
    for file in os.listdir("."):
        if file.endswith(".spec"):
            try:
                os.remove(file)
                print(f"  Removed {file}")
            except Exception as e:
                print(f"  Warning: Could not remove {file}: {str(e)}")

def main():
    """Main build function."""
    print("=" * 60)
    print("RateLoader GUI Exe Builder")
    print("=" * 60)
    
    # Check if we're in the right directory
    if not os.path.exists("gui/app.py"):
        print("❌ Error: gui/app.py not found. Please run this script from the project root.")
        return False
    
    # Clean previous builds
    clean_build()
    
    # Build the executable
    success = build_exe()
    
    if success:
        print("\n" + "=" * 60)
        print("🎉 BUILD SUCCESSFUL!")
        print("=" * 60)
        print(f"Executable: dist/rateloader-gui.exe")
        print("\nTo run the application:")
        print("  1. Ensure Oracle client is installed")
        print("  2. Copy settings.ini to the same directory as the .exe")
        print("  3. Run: dist/rateloader-gui.exe")
        print("\nThe application will create a 'log/' directory next to the executable.")
    else:
        print("\n" + "=" * 60)
        print("❌ BUILD FAILED!")
        print("=" * 60)
        print("Please check the error messages above and try again.")
    
    return success

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
