#!/usr/bin/env python3
"""
psutil 없이 간단한 업데이트 테스트
"""

import os
import sys
import shutil
import tempfile
import time

def simple_update_test():
    """간단한 파일 교체 테스트"""
    print("=" * 60)
    print("Simple Update Test (without psutil)")
    print("=" * 60)
    
    temp_dir = tempfile.mkdtemp(prefix="simple_update_")
    print(f"Test directory: {temp_dir}")
    
    try:
        # 가짜 파일들 생성
        old_exe = os.path.join(temp_dir, "app.exe")
        new_exe = os.path.join(temp_dir, "app_new.exe")
        
        # 현재 버전 (8MB)
        with open(old_exe, 'wb') as f:
            f.write(b"OLD_VERSION_CONTENT_" + b"X" * (8 * 1024 * 1024))
        
        # 새 버전 (10MB)  
        with open(new_exe, 'wb') as f:
            f.write(b"NEW_VERSION_CONTENT_" + b"Y" * (10 * 1024 * 1024))
            
        print(f"Created files:")
        print(f"  app.exe: {os.path.getsize(old_exe):,} bytes")
        print(f"  app_new.exe: {os.path.getsize(new_exe):,} bytes")
        
        # 크기 검증
        new_size = os.path.getsize(new_exe)
        if new_size < 1024 * 1024:
            print(f"✗ New exe too small: {new_size} bytes")
            return False
        print(f"✓ Size verification passed: {new_size:,} bytes")
        
        # 백업 생성
        backup_path = f"{old_exe}.backup"
        shutil.copy2(old_exe, backup_path)
        print(f"✓ Backup created: {backup_path}")
        
        # 파일 교체 과정
        print("\nPerforming file replacement...")
        
        # 1. 기존 파일 삭제
        if os.path.exists(old_exe):
            os.remove(old_exe)
            print("✓ Old exe removed")
        
        # 2. 새 파일 이동
        shutil.move(new_exe, old_exe)
        print("✓ New exe moved to old location")
        
        # 3. 검증
        if not os.path.exists(old_exe):
            print("✗ ERROR: Updated exe file missing!")
            if os.path.exists(backup_path):
                shutil.move(backup_path, old_exe)
                print("✓ Restored from backup")
            return False
            
        final_size = os.path.getsize(old_exe)
        print(f"✓ Final verification: {final_size:,} bytes")
        
        # 내용 확인
        with open(old_exe, 'rb') as f:
            content = f.read(50)
            content_str = content.decode('utf-8', errors='ignore')
            print(f"Content preview: {content_str}")
            
        if b"NEW_VERSION" in content:
            print("✓ Content verification successful - file properly replaced")
            
            # 백업 정리
            if os.path.exists(backup_path):
                os.remove(backup_path)
                print("✓ Backup cleaned up")
                
            return True
        else:
            print("✗ Content verification failed")
            return False
            
    except Exception as e:
        print(f"✗ Error during update: {e}")
        return False
    finally:
        shutil.rmtree(temp_dir, ignore_errors=True)
        print(f"Test directory cleaned up")

def test_launch_simulation():
    """새 실행 파일 시작 시뮬레이션"""
    print("\n" + "=" * 60)  
    print("Launch Simulation Test")
    print("=" * 60)
    
    temp_dir = tempfile.mkdtemp(prefix="launch_test_")
    
    try:
        # 가짜 실행 파일 생성
        test_exe = os.path.join(temp_dir, "test_app.exe")
        with open(test_exe, 'wb') as f:
            f.write(b"#!/bin/bash\necho 'App launched successfully'\nsleep 2\n")
        
        # 실행 권한 추가 (Linux에서)
        os.chmod(test_exe, 0o755)
        
        print(f"Created test executable: {test_exe}")
        
        # 실행 가능 여부 확인
        if os.path.exists(test_exe):
            print("✓ Executable file exists")
            print("✓ Launch simulation would succeed")
            return True
        else:
            print("✗ Executable file missing")
            return False
            
    except Exception as e:
        print(f"✗ Error in launch simulation: {e}")
        return False
    finally:
        shutil.rmtree(temp_dir, ignore_errors=True)

if __name__ == "__main__":
    print("Running simplified update tests...\n")
    
    # 파일 교체 테스트
    update_success = simple_update_test()
    
    # 실행 시뮬레이션 테스트
    launch_success = test_launch_simulation()
    
    print("\n" + "=" * 60)
    print("Test Results Summary")
    print("=" * 60)
    print(f"File replacement: {'✓ PASS' if update_success else '✗ FAIL'}")
    print(f"Launch simulation: {'✓ PASS' if launch_success else '✗ FAIL'}")
    
    if update_success and launch_success:
        print("\n✓ All tests passed - updater logic should work correctly")
    else:
        print("\n✗ Some tests failed - review updater implementation")