#!/usr/bin/env python3
"""
Updater 테스트 스크립트
실제 파일 교체 없이 updater 로직을 시뮬레이션
"""

import os
import sys
import shutil
import tempfile

def create_fake_exe(path, content="fake app content", size_mb=5):
    """가짜 exe 파일 생성"""
    content_bytes = content.encode('utf-8')
    # 지정된 크기까지 패딩
    target_size = size_mb * 1024 * 1024
    padding_size = max(0, target_size - len(content_bytes))
    padded_content = content_bytes + b'0' * padding_size
    
    with open(path, 'wb') as f:
        f.write(padded_content)
    print(f"Created fake exe: {path} ({os.path.getsize(path):,} bytes)")

def test_updater_logic():
    """Updater 로직 테스트"""
    print("=" * 60)
    print("Updater Logic Test")
    print("=" * 60)
    
    # 임시 디렉토리에서 테스트
    with tempfile.TemporaryDirectory() as temp_dir:
        print(f"Test directory: {temp_dir}")
        
        # 가짜 파일들 생성
        old_exe = os.path.join(temp_dir, "app.exe")
        new_exe = os.path.join(temp_dir, "app_new.exe")
        
        create_fake_exe(old_exe, "old version content", 10)
        create_fake_exe(new_exe, "new version content", 12)
        
        print(f"\nInitial state:")
        print(f"Old exe: {os.path.getsize(old_exe):,} bytes")
        print(f"New exe: {os.path.getsize(new_exe):,} bytes")
        
        # 백업 생성
        backup_path = f"{old_exe}.backup"
        shutil.copy2(old_exe, backup_path)
        print(f"Backup created: {backup_path}")
        
        # 파일 교체 시뮬레이션
        print(f"\nReplacing {old_exe} with {new_exe}...")
        
        try:
            # 기존 파일 삭제
            os.remove(old_exe)
            print("Old exe removed")
            
            # 새 파일로 교체
            shutil.move(new_exe, old_exe)
            print("New exe moved to old location")
            
            # 검증
            if os.path.exists(old_exe):
                final_size = os.path.getsize(old_exe)
                print(f"✓ Replacement successful: {final_size:,} bytes")
                
                # 내용 확인
                with open(old_exe, 'rb') as f:
                    content = f.read(50).decode('utf-8', errors='ignore')
                    print(f"Content preview: {content}")
                    
                if "new version" in content:
                    print("✓ Content verification successful")
                else:
                    print("✗ Content verification failed")
            else:
                print("✗ Replacement failed - file missing")
                
        except Exception as e:
            print(f"✗ Error during replacement: {e}")
            
            # 백업에서 복구
            if os.path.exists(backup_path):
                shutil.move(backup_path, old_exe)
                print("Restored from backup")
        
        # 정리
        if os.path.exists(backup_path):
            os.remove(backup_path)
            print("Backup cleaned up")
            
        print("\nTest completed!")

if __name__ == "__main__":
    test_updater_logic()