#!/usr/bin/env python3
"""
시스템 트레이 아이콘 설정 도우미
필요한 라이브러리를 설치하고 트레이 아이콘 기능을 테스트합니다.
"""

import sys
import subprocess
import importlib.util
import os

def check_library(library_name, package_name=None):
    """라이브러리가 설치되어 있는지 확인"""
    if package_name is None:
        package_name = library_name
    
    spec = importlib.util.find_spec(library_name)
    return spec is not None

def install_package(package_name):
    """패키지를 설치합니다"""
    try:
        print(f"Installing {package_name}...")
        result = subprocess.run([
            sys.executable, "-m", "pip", "install", package_name
        ], capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"✓ {package_name} installed successfully")
            return True
        else:
            print(f"❌ Failed to install {package_name}")
            print(f"Error: {result.stderr}")
            return False
    except Exception as e:
        print(f"❌ Exception during installation: {e}")
        return False

def install_system_packages():
    """시스템 패키지 설치 (Linux)"""
    if os.name == 'posix':  # Linux/Unix
        print("Trying to install system packages (Linux)...")
        try:
            # Ubuntu/Debian 계열
            subprocess.run([
                "sudo", "apt", "install", "-y", 
                "python3-tk", "python3-pil", "python3-dev"
            ], check=False)
            print("System packages installation attempted")
        except:
            print("Could not install system packages automatically")

def main():
    print("="*60)
    print("🖥️  GeoMedical Helper - System Tray Setup")
    print("="*60)
    
    # 필요한 라이브러리 목록
    libraries = [
        ("pystray", "pystray"),
        ("PIL", "pillow"),
        ("tkinter", None)  # 시스템 패키지
    ]
    
    missing_libraries = []
    
    # 라이브러리 확인
    print("\n1. Checking installed libraries...")
    for lib_name, package_name in libraries:
        if check_library(lib_name):
            print(f"✓ {lib_name} is installed")
        else:
            print(f"❌ {lib_name} is NOT installed")
            if package_name:
                missing_libraries.append(package_name)
            else:
                print(f"   Note: {lib_name} requires system package installation")
    
    # 누락된 라이브러리 설치
    if missing_libraries:
        print(f"\n2. Installing missing libraries: {', '.join(missing_libraries)}")
        success_count = 0
        
        for package in missing_libraries:
            if install_package(package):
                success_count += 1
        
        if success_count == len(missing_libraries):
            print("✓ All libraries installed successfully!")
        else:
            print("⚠️ Some libraries failed to install")
            print("\nAlternative installation methods:")
            print("- Use virtual environment: python -m venv venv && source venv/bin/activate")
            print("- Install with --user flag: pip install --user pystray pillow")
            print("- Use system packages (Linux): sudo apt install python3-tk python3-pil")
    
    # tkinter 확인 (특별 처리)
    if not check_library("tkinter"):
        print("\n⚠️ tkinter is not available")
        if os.name == 'posix':
            print("Try installing: sudo apt install python3-tk")
        else:
            print("tkinter should be included with Python on Windows/macOS")
    
    # 최종 확인
    print("\n3. Final verification...")
    all_ok = True
    for lib_name, _ in libraries:
        if lib_name == "tkinter":
            continue  # tkinter는 선택사항
        if check_library(lib_name):
            print(f"✓ {lib_name} verified")
        else:
            print(f"❌ {lib_name} still missing")
            all_ok = False
    
    # 결과
    print("\n" + "="*60)
    if all_ok:
        print("🎉 Setup completed successfully!")
        print("You can now run: python app.py")
        print("The system tray icon should appear in your taskbar.")
    else:
        print("⚠️ Setup incomplete, but the program will work with console interface")
        print("Run: python app.py")
        print("You'll see a console interface instead of system tray icon.")
    
    print("\nFor more help, see: install_dependencies.md")
    print("="*60)

if __name__ == "__main__":
    main()