#!/usr/bin/env python
"""
Script to check if Python is installed and verify dependencies.
This script assumes Python is already available and focuses on dependency checking.
"""

import os
import subprocess
import sys
import pkg_resources

def check_python_version():
    """Check Python version and ensure it meets minimum requirements."""
    try:
        result = subprocess.run([sys.executable, "--version"], capture_output=True, text=True, check=True)
        version_str = result.stdout.strip().replace("Python", "").strip()
        
        # Parse version
        major, minor, _ = map(int, version_str.split('.'))
        
        if major < 3 or (major == 3 and minor < 9):
            print(f"[ERROR] Python {version_str} is too old. Excel Filter Tool requires Python 3.9 or later.")
            return False
        else:
            print(f"[SUCCESS] Python {version_str} is compatible.")
            return True
            
    except Exception as e:
        print(f"[ERROR] checking Python version: {e}")
        return False

def check_dependencies():
    """Check if all required Python packages are installed."""
    required_packages = {
        'pandas': 'Data analysis library',
        'openpyxl': 'Excel file handling',
        'customtkinter': 'Modern UI components',
    }
    
    missing_packages = []
    
    print("Checking required Python packages...")
    
    for package, description in required_packages.items():
        try:
            pkg_resources.get_distribution(package)
            print(f"[SUCCESS] {package} ({description}) - installed")
        except pkg_resources.DistributionNotFound:
            print(f"[ERROR] {package} ({description}) - NOT installed")
            missing_packages.append(package)
    
    return missing_packages

def install_missing_dependencies(missing_packages):
    """Install missing Python packages."""
    if not missing_packages:
        return True
    
    print(f"\n🔧 Installing {len(missing_packages)} missing package(s)...")
    
    try:
        for package in missing_packages:
            print(f"Installing {package}...")
            subprocess.run([sys.executable, "-m", "pip", "install", package], check=True)
            print(f"[SUCCESS] {package} installed successfully")
        
        return True
    except subprocess.CalledProcessError as e:
        print(f"[ERROR] Failed to install packages: {e}")
        return False
    except Exception as e:
        print(f"[ERROR] Unexpected error during installation: {e}")
        return False

def check_tkinter():
    """Check if Tkinter is available (it's part of standard library but sometimes missing)."""
    try:
        import tkinter
        from tkinter import ttk
        print("[SUCCESS] Tkinter (GUI library) - available")
        return True
    except ImportError:
        print("[ERROR] Tkinter (GUI library) - NOT available")
        print("   Note: Tkinter is required for the graphical interface")
        return False
    except Exception as e:
        print(f"[ERROR] Error checking Tkinter: {e}")
        return False

def main():
    """Main function to check Python environment."""
    print("Excel Filter Tool - Python Environment Check")
    print("=" * 50)
    
    # Check Python version
    python_ok = check_python_version()
    if not python_ok:
        print("\nPlease install Python 3.9 or later from:")
        print("   https://www.python.org/downloads/")
        print("   Make sure to check 'Add Python to PATH' during installation")
        return False
    
    # Check Tkinter
    tkinter_ok = check_tkinter()
    
    # Check other dependencies
    missing_packages = check_dependencies()
    
    # Install missing dependencies if any
    if missing_packages:
        install_success = install_missing_dependencies(missing_packages)
        if not install_success:
            print(f"\n[WARNING]  Some dependencies could not be installed automatically")
            print("   You may need to install them manually using:")
            print("   pip install " + " ".join(missing_packages))
            return False
    
    # Final summary
    print("\n" + "=" * 50)
    if python_ok and tkinter_ok and not missing_packages:
        print("[SUCCESS] All checks passed! Excel Filter Tool is ready to use.")
        return True
    else:
        print("[WARNING]  Some issues were found. Please review the messages above.")
        return False

if __name__ == "__main__":
    success = main()
    print(f"\nEnvironment check completed with status: {'SUCCESS' if success else 'ISSUES_FOUND'}")
    sys.exit(0 if success else 1)