#!/usr/bin/env python3
"""
app.exe 실행 문제 디버깅 스크립트
"""

import os
import sys
import subprocess
import time

def debug_app_exe(app_path):
    """app.exe 실행 문제를 디버깅합니다"""
    print("=" * 60)
    print("GeoMedical App.exe Debug Tool")
    print("=" * 60)
    
    app_path = os.path.abspath(app_path)
    print(f"Target executable: {app_path}")
    
    # 1. 파일 존재 확인
    if not os.path.exists(app_path):
        print("✗ ERROR: app.exe file not found")
        return False
    print("✓ File exists")
    
    # 2. 파일 크기 확인
    file_size = os.path.getsize(app_path)
    print(f"✓ File size: {file_size:,} bytes ({file_size // (1024*1024)} MB)")
    
    # 3. PE 헤더 확인
    try:
        with open(app_path, 'rb') as f:
            header = f.read(64)
            if header.startswith(b'MZ'):
                print("✓ Valid PE executable header")
            else:
                print("✗ Invalid PE header")
                return False
    except Exception as e:
        print(f"✗ Error reading file: {e}")
        return False
    
    # 4. 파일 권한 확인
    if os.access(app_path, os.X_OK):
        print("✓ File has execute permissions")
    else:
        print("⚠ File may not have execute permissions")
    
    # 5. 의존성 확인 (간접적)
    print("\n--- Testing executable validity ---")
    
    # 5.1. 빠른 실행 테스트 (--help 시도)
    try:
        print("Testing with --help flag...")
        result = subprocess.run([app_path, '--help'], 
                              capture_output=True, 
                              text=True, 
                              timeout=5,
                              cwd=os.path.dirname(app_path))
        
        print(f"Return code: {result.returncode}")
        if result.stdout:
            print(f"STDOUT preview: {result.stdout[:200]}...")
        if result.stderr:
            print(f"STDERR: {result.stderr[:200]}...")
            
    except subprocess.TimeoutExpired:
        print("⚠ Test timed out (app may be running)")
    except Exception as e:
        print(f"✗ Test execution failed: {e}")
        return False
    
    # 5.2. 버전 테스트
    try:
        print("\nTesting with --version flag...")
        result = subprocess.run([app_path, '--version'], 
                              capture_output=True, 
                              text=True, 
                              timeout=5,
                              cwd=os.path.dirname(app_path))
        
        print(f"Return code: {result.returncode}")
        if result.stdout:
            print(f"Version output: {result.stdout.strip()}")
        if result.stderr:
            print(f"STDERR: {result.stderr.strip()}")
            
    except subprocess.TimeoutExpired:
        print("⚠ Version test timed out")
    except Exception as e:
        print(f"Version test failed: {e}")
    
    # 6. 실제 실행 테스트
    print("\n--- Attempting actual launch ---")
    
    try:
        print("Starting app.exe in new console...")
        
        # Windows start 명령 사용 (따옴표 문제 해결)
        app_dir = os.path.dirname(app_path)
        start_cmd = ['cmd', '/c', 'start', 'GeoMedical Debug', '/D', app_dir, app_path]
        print(f"Command: {' '.join(start_cmd)}")
        
        result = subprocess.run(start_cmd, 
                              cwd=app_dir,
                              capture_output=True, 
                              text=True, 
                              timeout=10)
        
        if result.returncode == 0:
            print("✓ Start command executed successfully")
            
            # 프로세스 확인
            print("Waiting 3 seconds to check if process started...")
            time.sleep(3)
            
            # 프로세스 목록 확인
            try:
                tasklist_result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq app.exe'], 
                                               capture_output=True, text=True)
                if 'app.exe' in tasklist_result.stdout:
                    print("✓ app.exe process is running!")
                    return True
                else:
                    print("✗ app.exe process not found in task list")
                    
            except Exception as e:
                print(f"Error checking process list: {e}")
                
        else:
            print(f"✗ Start command failed with code {result.returncode}")
            if result.stderr:
                print(f"Error: {result.stderr}")
                
    except Exception as e:
        print(f"✗ Launch test failed: {e}")
    
    print("\n--- Manual launch instructions ---")
    print(f"Try manually running:")
    print(f"1. Open Command Prompt")
    print(f"2. cd /d \"{os.path.dirname(app_path)}\"")
    print(f"3. app.exe")
    print(f"4. Check for any error messages")
    
    return False

def main():
    if len(sys.argv) != 2:
        print("Usage: python debug_app_launch.py <path_to_app.exe>")
        print("Example: python debug_app_launch.py J:\\python\\help\\dist\\app.exe")
        sys.exit(1)
    
    app_path = sys.argv[1]
    success = debug_app_exe(app_path)
    
    if success:
        print("\n✅ App.exe appears to be working correctly")
    else:
        print("\n❌ App.exe has issues that need to be resolved")
        print("\nPossible causes:")
        print("- Missing dependencies")
        print("- Corrupted file during update")
        print("- Antivirus interference") 
        print("- Windows permissions issues")
        print("- PyInstaller bundling problems")

if __name__ == "__main__":
    main()