#!/usr/bin/env python3
"""
Setup script for MBetter Discovery Application
Creates a standalone executable for Windows and Linux
"""

import sys
import os
import subprocess
from pathlib import Path

def install_requirements():
    """Install required packages"""
    requirements = [
        "PyQt6>=6.4.0",
        "netifaces>=0.11.0"
    ]
    
    print("Installing required packages...")
    for req in requirements:
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", req])
            print(f"✓ {req} installed")
        except subprocess.CalledProcessError as e:
            print(f"✗ Failed to install {req}: {e}")
            return False
    
    return True

def create_icon():
    """Create application icon"""
    try:
        print("Creating application icon...")
        
        # Check if Pillow is available
        try:
            import PIL
            print("✓ Pillow is available")
        except ImportError:
            print("Installing Pillow for icon creation...")
            subprocess.check_call([sys.executable, "-m", "pip", "install", "Pillow"])
        
        # Run icon creation script
        if os.path.exists("create_icon.py"):
            subprocess.check_call([sys.executable, "create_icon.py"])
            print("✓ Icon created successfully")
            return True
        else:
            print("⚠ create_icon.py not found, skipping icon creation")
            return True
            
    except subprocess.CalledProcessError as e:
        print(f"⚠ Icon creation failed: {e}")
        return True  # Don't fail the build if icon creation fails

def create_executable():
    """Create executable using PyInstaller with spec files"""
    try:
        # Check if PyInstaller is available
        subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
        
        print("Creating executable...")
        
        # Create icon first (especially important for Windows)
        create_icon()
        
        # Determine platform and spec file
        if sys.platform.startswith("win"):
            spec_file = "mbetter_discovery_windows.spec"
            platform_name = "Windows"
        else:
            spec_file = "mbetter_discovery_linux.spec"
            platform_name = "Linux"
        
        if not os.path.exists(spec_file):
            print(f"✗ Spec file {spec_file} not found")
            return False
        
        print(f"Building for {platform_name} using {spec_file}...")
        
        # PyInstaller command with spec file
        cmd = [sys.executable, "-m", "PyInstaller", spec_file]
        
        subprocess.check_call(cmd)
        print("✓ Executable created in dist/ directory")
        
        # Show executable location
        if sys.platform.startswith("win"):
            exe_path = "dist/MBetterDiscovery.exe"
        else:
            exe_path = "dist/MBetterDiscovery"
        
        if os.path.exists(exe_path):
            print(f"✓ Executable location: {exe_path}")
            
            # Show file size
            file_size = os.path.getsize(exe_path)
            size_mb = file_size / (1024 * 1024)
            print(f"  File size: {size_mb:.1f} MB")
        
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"✗ Failed to create executable: {e}")
        return False

def create_batch_file():
    """Create Windows batch file for easy running"""
    batch_content = """@echo off
echo Starting MBetter Discovery...
python mbetter_discovery.py
if %errorlevel% neq 0 (
    echo.
    echo Error: Python or required packages not found
    echo Please run setup_discovery.py first to install requirements
    echo.
    pause
)
"""
    
    with open("run_discovery.bat", "w") as f:
        f.write(batch_content)
    
    print("✓ Created run_discovery.bat for Windows")

def create_shell_script():
    """Create Linux shell script for easy running"""
    shell_content = """#!/bin/bash
echo "Starting MBetter Discovery..."
python3 mbetter_discovery.py
if [ $? -ne 0 ]; then
    echo
    echo "Error: Python3 or required packages not found"
    echo "Please run: python3 setup_discovery.py"
    echo
    read -p "Press Enter to continue..."
fi
"""
    
    with open("run_discovery.sh", "w") as f:
        f.write(shell_content)
    
    # Make executable
    os.chmod("run_discovery.sh", 0o755)
    print("✓ Created run_discovery.sh for Linux")

def main():
    """Main setup function"""
    print("=" * 50)
    print("MBetter Discovery Application Setup")
    print("=" * 50)
    
    # Install requirements
    if not install_requirements():
        print("\n✗ Setup failed - could not install requirements")
        return False
    
    # Create platform-specific run scripts
    if sys.platform.startswith("win"):
        create_batch_file()
    else:
        create_shell_script()
    
    # Ask if user wants to create executable
    create_exe = input("\nDo you want to create a standalone executable? (y/n): ").lower().strip()
    if create_exe in ('y', 'yes'):
        if create_executable():
            print("\n✓ Setup completed successfully!")
            print("You can run the executable from the dist/ directory")
        else:
            print("\n⚠ Setup completed with warnings - executable creation failed")
            print("You can still run the application with the scripts created")
    else:
        print("\n✓ Setup completed successfully!")
        if sys.platform.startswith("win"):
            print("Run the application with: run_discovery.bat")
        else:
            print("Run the application with: ./run_discovery.sh")
    
    return True

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\nSetup interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n✗ Setup failed with error: {e}")
        sys.exit(1)