#!/usr/bin/env python3
"""
전체 업데이트 플로우 테스트
"""

import os
import sys
import subprocess
import tempfile
import shutil
import time

def create_test_files():
    """테스트용 파일들 생성"""
    temp_dir = tempfile.mkdtemp(prefix="geomedical_test_")
    print(f"Test directory: {temp_dir}")
    
    # 가짜 app.exe (현재 버전)
    old_app = os.path.join(temp_dir, "app.exe")
    with open(old_app, 'wb') as f:
        content = b"OLD VERSION " + b"X" * (8 * 1024 * 1024)  # 8MB
        f.write(content)
    print(f"Created old app.exe: {os.path.getsize(old_app):,} bytes")
    
    # 가짜 app_new.exe (새 버전)
    new_app = os.path.join(temp_dir, "app_new.exe")
    with open(new_app, 'wb') as f:
        content = b"NEW VERSION " + b"Y" * (10 * 1024 * 1024)  # 10MB
        f.write(content)
    print(f"Created new app_new.exe: {os.path.getsize(new_app):,} bytes")
    
    # updater.py 복사
    updater_py = os.path.join(temp_dir, "updater.py")
    shutil.copy2("/mnt/c/Users/Administrator/Desktop/help_/updater.py", updater_py)
    print(f"Copied updater.py")
    
    return temp_dir, old_app, new_app, updater_py

def test_updater_directly():
    """updater.py를 직접 실행해서 테스트"""
    print("=" * 60)
    print("Direct Updater Test")
    print("=" * 60)
    
    temp_dir, old_app, new_app, updater_py = create_test_files()
    
    try:
        # 가짜 PID (현재 프로세스)
        fake_pid = os.getpid()
        
        print(f"Testing updater with:")
        print(f"  PID: {fake_pid}")
        print(f"  Old exe: {old_app}")
        print(f"  New exe: {new_app}")
        
        # updater.py 실행
        cmd = [
            sys.executable, updater_py,
            "--pid", str(fake_pid),
            "--old-exe", old_app,
            "--new-exe", new_app,
            "--auto-launch"
        ]
        
        print(f"\nRunning: {' '.join(cmd)}")
        
        # 별도 프로세스에서 실행
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        
        print(f"\nUpdater output:")
        print("STDOUT:", result.stdout)
        if result.stderr:
            print("STDERR:", result.stderr)
        print(f"Return code: {result.returncode}")
        
        # 결과 확인
        if os.path.exists(old_app):
            final_size = os.path.getsize(old_app)
            print(f"\nFinal app.exe size: {final_size:,} bytes")
            
            with open(old_app, 'rb') as f:
                content = f.read(20).decode('utf-8', errors='ignore')
                print(f"Content preview: {content}")
                
            if "NEW VERSION" in content:
                print("✓ Update successful - content matches new version")
            else:
                print("✗ Update failed - content still old version")
        else:
            print("✗ app.exe missing after update")
            
    except subprocess.TimeoutExpired:
        print("✗ Updater process timed out")
    except Exception as e:
        print(f"✗ Error running updater: {e}")
    finally:
        # 정리
        shutil.rmtree(temp_dir, ignore_errors=True)
        print(f"Cleaned up test directory")

if __name__ == "__main__":
    test_updater_directly()