import socketio
import requests
import time
import json

# Test API
def test_api():
    print("Testing API...")
    # Simulate a link request
    # Note: This will fail if the code is not in the server's memory, 
    # but we just want to see if the endpoint is reachable.
    try:
        response = requests.post('http://localhost:5000/api/link', json={
            'code': 'TESTCODE',
            'uuid': 'test-uuid',
            'username': 'TestPlayer'
        })
        print(f"API Response: {response.status_code} - {response.json()}")
    except Exception as e:
        print(f"API Connection Failed: {e}")

# Test WebSocket
def test_websocket():
    print("Testing WebSocket...")
    sio = socketio.Client()

    @sio.event
    def connect():
        print("WebSocket Connected!")
        # Send a test event
        sio.emit('game_event', {
            'type': 'CHAT',
            'player': 'TestPlayer',
            'uuid': 'test-uuid',
            'content': 'Hello from test script!'
        })
        print("Test event sent.")
        sio.disconnect()

    @sio.event
    def connect_error(data):
        print(f"WebSocket Connection Failed: {data}")

    try:
        sio.connect('http://localhost:5000')
        sio.wait()
    except Exception as e:
        print(f"WebSocket Error: {e}")

if __name__ == "__main__":
    # Ensure the server is running before running this script
    test_api()
    test_websocket()
