
const fs = require('fs');

// Mock window/MagicBot
const callbacks = {};
global.window = {
    MagicBot: {
        state: {
            garden: {},
            inventory: {},
            shops: {}
        },
        events: {
            emit: (event, data) => {
                console.log(`[Event] ${event} emitted`);
                if (event === 'state_updated') {
                    // Check if shop restock time was updated
                    if (global.window.MagicBot.state.shops && global.window.MagicBot.state.shops.tool) {
                        console.log("Current Tool Restock Time:", global.window.MagicBot.state.shops.tool.secondsUntilRestock);
                    }
                }
            },
            dispatchEvent: () => { },
            addEventListener: () => { }
        },
        on: (event, callback) => {
            callbacks[event] = callback;
        },
        emit: (name, detail) => {
            // Mock the emit function we patched
            console.log(`[MB.emit] ${name}`);
            if (global.window.MagicBot.events.emit) {
                global.window.MagicBot.events.emit(name, detail);
            }
        }
    }
};

// Load modules
const stateJsContent = fs.readFileSync('/home/matiss/Documents/Code/magicbot/extension/modules/state.js', 'utf8');
eval(stateJsContent);

// Load Full State
const fullState = JSON.parse(fs.readFileSync('/home/matiss/Documents/Code/magicbot/fullstate.json', 'utf8'));

// 1. Simulate Welcome
console.log("\n--- Simulating Welcome ---");
callbacks['packet_received'](fullState);

// Check initial value
const initialRestock = global.window.MagicBot.state.shops.tool.secondsUntilRestock;
console.log("Initial Tool Restock Time:", initialRestock);

// 2. Simulate PartialState Patch
// User provided example: /child/data/shops/tool/secondsUntilRestock -> 380
const patchMsg = {
    "type": "PartialState",
    "patches": [
        { "op": "replace", "path": "/child/data/shops/tool/secondsUntilRestock", "value": 380 }
    ]
};

console.log("\n--- Simulating PartialState ---");
callbacks['packet_received'](patchMsg);

// Check final value
const finalRestock = global.window.MagicBot.state.shops.tool.secondsUntilRestock;
console.log("Final Tool Restock Time:", finalRestock);

if (finalRestock === 380) {
    console.log("SUCCESS: Patch applied.");
} else {
    console.error("FAILURE: Patch NOT applied. Expected 380, got " + finalRestock);
    process.exit(1);
}
