const WebSocket = require('ws');

const wsUrl = 'wss://magicgarden.gg/version/436ff68/api/rooms/NJMF/connect?surface=%22web%22&platform=%22desktop%22&playerId=%22p_WU9ea4LiMfR9AZsq%22&version=%22436ff68%22&source=%22router%22&capabilities=%22fbo_mipmap_unsupported%22';

console.log('Connecting to:', wsUrl);

const ws = new WebSocket(wsUrl, {
    headers: {
        'Host': 'magicgarden.gg',
        'Origin': 'https://magicgarden.gg',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36',
        'Cookie': 'mc_jwt=eyJhbGciOiJIUzI1NiJ9.eyJwcm92aWRlciI6ImRpc2NvcmQiLCJ1c2VySWQiOiI0MTk2Mjk0MDU5MDA2MzYxNzAiLCJ0b2tlblJlc3BvbnNlIjp7ImFjY2Vzc190b2tlbiI6Ik1USXlOemN4T1RZd05qSXlNemMyTlRZNE53LlpwRjdpMFRFN2xIQ05MRUgxN0MzTmpqTGFvbTNySCIsInRva2VuX3R5cGUiOiJCZWFyZXIiLCJleHBpcmVzX2luIjo2MDQ4MDAsInJlZnJlc2hfdG9rZW4iOiJMSGRKNXhTblQweGl6Y1l3anhZQzhOYW5pV0dWMUkiLCJzY29wZSI6Imd1aWxkcy5tZW1iZXJzLnJlYWQgZ3VpbGRzIGFwcGxpY2F0aW9ucy5jb21tYW5kcyBycGMudm9pY2UucmVhZCBpZGVudGlmeSJ9LCJkaXNjb3JkVXNlckZsYWdzIjowLCJvYnRhaW5lZEF0IjoxNzY0OTU5NjU3MjU0LCJpYXQiOjE3NjQ5NjQxNTAsImV4cCI6MTc5NjUyMTc1MH0.D2O3tdQRWL2LODjahK1B4MUJGAAaYjCxQzE1-eg_680; ph_phc_5NQnL0ALxa7n1xjFEeSAe3lMsL8gYu8c8F3RhgSiIkN_posthog=%7B%22distinct_id%22%3A%22419629405900636170%22%2C%22%24sesid%22%3A%5B1764964150683%2C%22019af00f-a521-78c9-976c-ae566391ae37%22%2C1764964148513%5D%2C%22%24epp%22%3Atrue%2C%22%24initial_person_info%22%3A%7B%22r%22%3A%22https%3A%2F%2Fwww.google.com%2F%22%2C%22u%22%3A%22https%3A%2F%2Fmagicgarden.gg%2Fr%2FQMQC%22%7D%7D'
    }
});

ws.on('open', function open() {
    console.log('Connected!');

    // Protocol confirmed by user capture
    // Handshake uses scopePath: ["Room"]
    const handshakeScope = ["Room"];
    const gameScope = ["Room", "Quinoa"];

    const voteMsg = {
        scopePath: handshakeScope,
        type: 'VoteForGame',
        gameName: 'Quinoa'
    };

    const selectMsg = {
        scopePath: handshakeScope,
        type: 'SetSelectedGame',
        gameName: 'Quinoa'
    };

    console.log('Sending Handshake 1:', JSON.stringify(voteMsg));
    ws.send(JSON.stringify(voteMsg));

    console.log('Sending Handshake 2:', JSON.stringify(selectMsg));
    ws.send(JSON.stringify(selectMsg));

    // Setup Client-Initiated Ping (Heartbeat)
    // Note: Pings might still use the specific game scope ["Room", "Quinoa"] once in game?
    // Let's try ["Room", "Quinoa"] for pings as seen in previous logs, or ["Room"] if that fails.
    // User logs showed: {"scopePath":["Room","Quinoa"],"type":"Ping"...}
    const pingScope = ["Room", "Quinoa"];

    const pingInterval = setInterval(() => {
        if (ws.readyState !== WebSocket.OPEN) return;
        const pingMsg = {
            type: "Ping",
            id: Date.now(),
            scopePath: pingScope
        };
        console.log('Sending Ping:', JSON.stringify(pingMsg));
        ws.send(JSON.stringify(pingMsg));
    }, 2000); // 2 seconds seems like a reasonable interval based on logs (303, 305 timestamps?)
});

ws.on('message', function message(data) {
    const msg = data.toString();
    console.log('Received:', msg.length > 200 ? msg.substring(0, 200) + '...' : msg);

    // Check if server sends us 'ping' string
    if (msg === 'ping') {
        console.log('Server ping -> Client pong');
        ws.send('pong');
    }
});

ws.on('error', function error(err) {
    console.error('Error:', err);
});

ws.on('close', function close() {
    console.log('Disconnected');
    process.exit(0);
});
