#!/usr/bin/env python3
"""
Windows start 명령어 테스트
"""

import subprocess
import os
import tempfile

def test_start_command():
    """Windows start 명령어 테스트"""
    print("=" * 60)
    print("Windows Start Command Test")
    print("=" * 60)
    
    # 임시 배치 파일 생성 (테스트용 실행 파일 역할)
    temp_dir = tempfile.mkdtemp()
    test_bat = os.path.join(temp_dir, "test_app.bat")
    
    with open(test_bat, 'w', encoding='cp949') as f:
        f.write("""@echo off
echo Test application started successfully!
echo Working directory: %CD%
echo Arguments: %*
timeout /t 3 /nobreak >nul
echo Test application exiting...
""")
    
    print(f"Created test file: {test_bat}")
    
    # 방법 1: 잘못된 방법 (문자열로 조합)
    print("\n--- Test 1: String concatenation (problematic) ---")
    try:
        wrong_cmd = f'start "Test App" /D "{temp_dir}" "{test_bat}"'
        print(f"Command: cmd /c {wrong_cmd}")
        
        result = subprocess.run(['cmd', '/c', wrong_cmd], 
                              capture_output=True, text=True, timeout=10)
        
        print(f"Return code: {result.returncode}")
        if result.stderr:
            print(f"STDERR: {result.stderr}")
        if result.returncode == 0:
            print("✓ String method worked")
        else:
            print("✗ String method failed")
            
    except Exception as e:
        print(f"✗ String method error: {e}")
    
    # 방법 2: 올바른 방법 (리스트로 분리)
    print("\n--- Test 2: List arguments (correct) ---")
    try:
        correct_cmd = ['cmd', '/c', 'start', 'Test App', '/D', temp_dir, test_bat]
        print(f"Command: {' '.join(correct_cmd)}")
        
        result = subprocess.run(correct_cmd, 
                              capture_output=True, text=True, timeout=10)
        
        print(f"Return code: {result.returncode}")
        if result.stderr:
            print(f"STDERR: {result.stderr}")
        if result.returncode == 0:
            print("✓ List method worked")
        else:
            print("✗ List method failed")
            
    except Exception as e:
        print(f"✗ List method error: {e}")
    
    # 방법 3: 직접 Popen (대안)
    print("\n--- Test 3: Direct Popen ---")
    try:
        print(f"Command: {test_bat}")
        process = subprocess.Popen([test_bat], 
                                 cwd=temp_dir,
                                 creationflags=subprocess.CREATE_NEW_CONSOLE)
        print(f"✓ Direct Popen started with PID: {process.pid}")
        
    except Exception as e:
        print(f"✗ Direct Popen error: {e}")
    
    # 정리
    try:
        os.remove(test_bat)
        os.rmdir(temp_dir)
    except:
        pass
    
    print("\n--- Recommendations ---")
    print("✓ Use list arguments instead of string concatenation")
    print("✓ Always test with actual file paths that contain spaces")
    print("✓ Have fallback methods for different scenarios")

if __name__ == "__main__":
    test_start_command()