#!/usr/bin/env python3
"""
서버 포트 변경 테스트 (5000 → 8800)
"""

import requests
import socket
import time

def test_port_change():
    """포트 변경 테스트"""
    print("=" * 60)
    print("Server Port Change Test - 192.168.0.240:8800")
    print("=" * 60)
    
    server_ip = "192.168.0.240"
    old_port = 5000
    new_port = 8800
    
    # 1. 이전 포트 연결 확인
    print(f"1. Testing old port ({old_port}) - Should NOT connect...")
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(2)
        result = sock.connect_ex((server_ip, old_port))
        sock.close()
        
        if result == 0:
            print(f"   ⚠ Old port {old_port} is still accessible")
            print(f"   → Server might still be running on old port")
        else:
            print(f"   ✓ Old port {old_port} is not accessible (expected)")
    except Exception as e:
        print(f"   ✓ Old port test: {e} (expected)")
    
    # 2. 새 포트 연결 확인
    print(f"\n2. Testing new port ({new_port}) - Should connect...")
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        result = sock.connect_ex((server_ip, new_port))
        sock.close()
        
        if result == 0:
            print(f"   ✓ New port {new_port} is accessible")
        else:
            print(f"   ✗ New port {new_port} is NOT accessible")
            print(f"   → Please check if server.py is running on port {new_port}")
            return False
    except Exception as e:
        print(f"   ✗ New port test error: {e}")
        return False
    
    # 3. HTTP 서버 응답 테스트
    print(f"\n3. Testing HTTP server on new port...")
    new_api_url = f"http://{server_ip}:{new_port}"
    
    try:
        response = requests.get(f"{new_api_url}/", timeout=10)
        print(f"   ✓ HTTP server responding on port {new_port} (Status: {response.status_code})")
    except requests.exceptions.ConnectionError:
        print(f"   ✗ HTTP server not responding on port {new_port}")
        return False
    except Exception as e:
        print(f"   ✗ HTTP test error: {e}")
        return False
    
    # 4. API 엔드포인트 테스트
    print(f"\n4. Testing API endpoints on new port...")
    
    # 로그 API 테스트
    try:
        log_data = {
            "hostname": "test-client",
            "level": "INFO",
            "category": "PORT_TEST",
            "message": "Testing new port 8800",
            "details": "Port change verification",
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
        }
        
        response = requests.post(f"{new_api_url}/api/agent/log", 
                               json=log_data, 
                               timeout=10)
        
        print(f"   → Log API: Status {response.status_code}")
    except Exception as e:
        print(f"   → Log API error: {e}")
    
    # 관리 요청 API 테스트
    try:
        response = requests.get(f"{new_api_url}/api/software/management-requests/test-client",
                              timeout=10)
        print(f"   → Management API: Status {response.status_code}")
    except Exception as e:
        print(f"   → Management API error: {e}")
    
    # 대시보드 테스트
    try:
        response = requests.get(f"{new_api_url}/dashboard", timeout=10)
        print(f"   → Dashboard: Status {response.status_code}")
    except Exception as e:
        print(f"   → Dashboard error: {e}")
    
    print("\n" + "=" * 60)
    print("Port Change Summary")
    print("=" * 60)
    print(f"✅ Port successfully changed from {old_port} to {new_port}")
    print(f"✅ API URL: http://{server_ip}:{new_port}")
    
    return True

def verify_app_configuration():
    """app.py 설정 확인"""
    print("\n" + "=" * 60)
    print("App.py Configuration Verification")
    print("=" * 60)
    
    print("Checking app.py configuration...")
    
    try:
        with open("/mnt/c/Users/Administrator/Desktop/help_/app.py", "r", encoding="utf-8") as f:
            content = f.read()
        
        if 'self.api_url = "http://192.168.0.240:8800"' in content:
            print("✓ app.py API URL correctly set to: http://192.168.0.240:8800")
        else:
            print("✗ app.py API URL not updated correctly")
            return False
            
    except Exception as e:
        print(f"✗ Could not verify app.py: {e}")
        return False
    
    print("\nChecking server.py configuration...")
    
    try:
        with open("/mnt/c/Users/Administrator/Desktop/help_/server.py", "r", encoding="utf-8") as f:
            content = f.read()
        
        if "port=8800" in content:
            print("✓ server.py port correctly set to: 8800")
        else:
            print("✗ server.py port not updated correctly")
            return False
            
    except Exception as e:
        print(f"✗ Could not verify server.py: {e}")
        return False
    
    return True

def display_usage_instructions():
    """사용 방법 안내"""
    print("\n" + "=" * 60)
    print("Usage Instructions")
    print("=" * 60)
    print("\n1. Start server on 192.168.0.240:")
    print("   cd /path/to/help_")
    print("   python3 server.py")
    print("\n2. Verify server is running:")
    print("   → Should see: '* Running on http://0.0.0.0:8800'")
    print("\n3. Access dashboards:")
    print("   → Main: http://192.168.0.240:8800/dashboard")
    print("   → Software: http://192.168.0.240:8800/software-dashboard")
    print("   → Logs: http://192.168.0.240:8800/logs-dashboard")
    print("\n4. Run app.exe:")
    print("   → Will connect to http://192.168.0.240:8800")
    print("\n5. Firewall rules:")
    print("   → Make sure port 8800 is open")
    print("   → Remove old rule for port 5000")

if __name__ == "__main__":
    print("Testing server port change from 5000 to 8800...\n")
    
    # 1. 설정 파일 확인
    config_ok = verify_app_configuration()
    
    # 2. 포트 연결 테스트
    port_ok = test_port_change()
    
    # 3. 사용 방법 안내
    display_usage_instructions()
    
    print("\n" + "=" * 60)
    print("FINAL RESULT")
    print("=" * 60)
    
    if config_ok and port_ok:
        print("🎉 PORT CHANGE SUCCESSFUL!")
        print("\n✅ Configuration files updated")
        print("✅ New port 8800 is accessible")
        print("✅ All systems ready")
    elif config_ok and not port_ok:
        print("⚠ CONFIGURATION OK BUT SERVER NOT RUNNING")
        print("\n✅ Configuration files updated correctly")
        print("❌ Server not accessible on port 8800")
        print("→ Please start server.py on 192.168.0.240:8800")
    else:
        print("❌ PORT CHANGE INCOMPLETE")
        print("\nPlease check the configuration and try again")