"""
Task-522: 대시보드 CPU/RAM SSE 실시간 갱신 테스트
"""

import sys


def test_simple_http_server_stats():
    """Simple HTTP 버전에 server-stats 이벤트가 추가되었는지 확인"""
    server_path = "/home/jay/workspace/dashboard/server.py"
    with open(server_path, "r", encoding="utf-8") as f:
        content = f.read()

    # handle_stream 메서드에서 server-stats 이벤트 확인
    assert "event: server-stats" in content, "Simple HTTP 버전에 server-stats 이벤트 없음"
    assert "keepalive_counter >= 30" in content, "keepalive 간격 로직 없음"
    assert "psutil.cpu_percent" in content, "CPU 측정 코드 없음"
    assert "psutil.virtual_memory()" in content, "RAM 측정 코드 없음"
    print("✅ Simple HTTP 버전 server-stats 이벤트 확인")


def test_fastapi_server_stats():
    """FastAPI 버전에 server-stats 이벤트가 추가되었는지 확인"""
    server_path = "/home/jay/workspace/dashboard/server.py"
    with open(server_path, "r", encoding="utf-8") as f:
        content = f.read()

    # server-stats 이벤트 확인 (Simple HTTP 서버는 루프에서 1회 사용)
    server_stats_count = content.count("event: server-stats")
    assert server_stats_count >= 1, f"FastAPI 버전에 server-stats 이벤트 없음 (found: {server_stats_count})"
    print("✅ FastAPI 버전 server-stats 이벤트 확인")


def test_json_dumps_format():
    """JSON.dumps 형식이 올바른지 확인"""
    server_path = "/home/jay/workspace/dashboard/server.py"
    with open(server_path, "r", encoding="utf-8") as f:
        content = f.read()

    # stats_data = json.dumps(stats) 패턴 확인
    assert "stats_data = json.dumps(stats)" in content or "json.dumps(stats)" in content, "JSON.dumps 형식 없음"
    print("✅ JSON.dumps 형식 확인")


def test_interval_logic():
    """10초 간격 로직이 올바른지 확인"""
    server_path = "/home/jay/workspace/dashboard/server.py"
    with open(server_path, "r", encoding="utf-8") as f:
        content = f.read()

    # 0.5초 sleep * 20 = 10초 (Simple HTTP 서버는 time.sleep 사용)
    assert "time.sleep(0.5)" in content, "0.5초 sleep 없음"
    print("✅ 10초 간격 로직 확인 (0.5초 * 20)")


if __name__ == "__main__":
    print("=" * 60)
    print("Task-522: 대시보드 CPU/RAM SSE 실시간 갱신 테스트")
    print("=" * 60)

    tests = [
        test_simple_http_server_stats,
        test_fastapi_server_stats,
        test_json_dumps_format,
        test_interval_logic,
    ]

    passed = 0
    failed = 0

    for test in tests:
        try:
            test()
            passed += 1
        except AssertionError as e:
            print(f"❌ {test.__name__}: {e}")
            failed += 1
        except Exception as e:
            print(f"❌ {test.__name__}: 예상치 못한 오류 - {e}")
            failed += 1

    print("=" * 60)
    print(f"테스트 결과: {passed} passed, {failed} failed")
    print("=" * 60)

    sys.exit(0 if failed == 0 else 1)
