const fs = require('fs');
const path = require('path');
const { Rpc } = require('@entityseven/rage-fw-rpc');

const rpc = new Rpc();
let settings;

try {
    const settingsPath = path.resolve(__dirname, '../../settings.json');
    const data = fs.readFileSync(settingsPath, 'utf8');
    settings = JSON.parse(data);
    console.log('[Core] Loaded settings.json successfully.');
} catch (e) {
    console.error('[Core] Failed to load settings.json:', e);
    settings = { cef: 'dev', debugger: true };
}

mp.events.add('playerReady', (player) => {
    console.log(`[Core] Player ${player.name} joined. Initializing CEF via Rpc...`);
    
    // Determine the CEF URL based on settings
    const isDev = settings.cef === 'dev';
    const cefUrl = isDev ? 'http://localhost:3000' : 'package://cef/index.html';
    
    // Give the client a tiny bit of time to fully load scripts before calling
    setTimeout(() => {
        if (!mp.players.exists(player)) return;
        player.call('client:initCef', [cefUrl, !!settings.debugger]);
        console.log(`[Core] CEF initialization event sent to ${player.name}`);
    }, 500);
});

// Custom Chat Backend
rpc.register('server:chat:receive', (player, msg) => {
    if (msg.startsWith('/')) {
        console.log(`[Command] ${player.name}: ${msg}`);
        // Command execution logic can be wired here later
        rpc.callClient(player, 'chat:push:custom', [{
            type: 'error',
            text: 'Commands are not fully implemented in the custom chat yet.'
        }]).catch(() => {});
        return true;
    }

    // Broadcast structured message to all players
    const chatData = {
        type: 'player',
        name: player.name,
        id: player.id,
        text: msg,
        timestamp: Date.now()
    };
    
    mp.players.forEach((p) => {
        rpc.callClient(p, 'chat:push:custom', [chatData]).catch(() => {});
    });
    
    return true;
});

// Example RPC handler
rpc.register('server:test', (player, msg) => {
    console.log(`[RPC] Received from ${player.name}: ${msg}`);
    return `Server received: ${msg}`;
});
