(function () {
    console.clear();
    console.log("%c Starting Magic Garden Traffic Capture... ", "background: #222; color: #bada55; font-size: 20px");

    // storage for logs
    window.capturedTraffic = [];

    // Hook WebSocket Constructor to catch NEW connections (Best for full session capture)
    const OriginalWebSocket = window.WebSocket;
    window.WebSocket = function (...args) {
        console.log("%c WS CONNECTING: " + args[0], "color: yellow");
        const socket = new OriginalWebSocket(...args);

        // Hook incoming messages
        socket.addEventListener('message', (event) => {
            const payload = {
                type: 'INCOMING',
                timestamp: Date.now(),
                data: event.data
            };
            window.capturedTraffic.push(payload);
            // Optional: Log to console to see it live (can be spammy)
            // console.log('%c < IN', 'color: green', event.data); 
        });

        // Hook outgoing messages
        const originalSend = socket.send;
        socket.send = function (data) {
            const payload = {
                type: 'OUTGOING',
                timestamp: Date.now(),
                data: data
            };
            window.capturedTraffic.push(payload);
            console.log('%c > OUT', 'color: cyan', data);
            originalSend.apply(this, arguments);
        };

        return socket;
    };

    // Copy prototype to ensure instanceof checks pass
    window.WebSocket.prototype = OriginalWebSocket.prototype;
    Object.keys(OriginalWebSocket).forEach(key => {
        window.WebSocket[key] = OriginalWebSocket[key];
    });

    // Helper to download the logs
    window.downloadTraffic = function () {
        const json = JSON.stringify(window.capturedTraffic, null, 2);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `magic_garden_traffic_${Date.now()}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        console.log(`%c Downloaded ${window.capturedTraffic.length} packets.`, "color: #bada55");
    };

    console.log("%c INSTRUCTIONS:", "font-weight: bold; font-size: 14px");
    console.log("1. The script is now active.");
    console.log("2. IMPORTANT: Refresh the page now to capture the initial connection handshake.");
    console.log("3. Play the game (move, farm, sell).");
    console.log("4. When done, type %c window.downloadTraffic() %c in the console to save the log file.", "background: #eee; color: black; padding: 2px", "");
})();
