#!/usr/bin/env node
/**
 * Test script — simulates a hub sending signals to the relay bridge.
 *
 * Usage:
 *   1. Start relay:  node relay-bridge.js
 *   2. Open browser: http://localhost:9876/index.html?ws=ws://localhost:9201
 *   3. Run this:     node test-hub.js
 *
 * This will:
 *   1. Push IR JSON (from app.ir.json) via UDP
 *   2. Send signal updates every 250ms
 *   3. Listen for panel events (action/touch)
 */

const dgram = require('dgram');
const fs = require('fs');
const path = require('path');

const UDP_PORT = 9200;
const client = dgram.createSocket('udp4');

// ─── Push IR JSON ───
const irPath = path.join(__dirname, 'app.ir.json');
if (fs.existsSync(irPath)) {
    const json = fs.readFileSync(irPath, 'utf8');
    const data = Buffer.from(json);

    // Build IR push frame: [D5][7A][40][00][len:u16LE][json...]
    const header = Buffer.alloc(6);
    header[0] = 0xD5;  // magic
    header[1] = 0x7A;  // magic
    header[2] = 0x40;  // DS_UDP_IR_PUSH
    header[3] = 0x00;  // reserved
    header.writeUInt16LE(data.length, 4);

    const frame = Buffer.concat([header, data]);
    client.send(frame, 0, frame.length, UDP_PORT, '127.0.0.1', () => {
        console.log(`[Hub] IR pushed (${data.length} bytes)`);
    });
} else {
    console.log('[Hub] No app.ir.json found, skipping IR push');
}

// ─── Send periodic signal updates ───
let tick = 0;

setInterval(() => {
    tick++;

    // Signal 6 (ticks) — increment every second
    if (tick % 4 === 0) {
        const sigFrame = Buffer.alloc(7);
        sigFrame[0] = 0x20;  // DS_NOW_SIG
        sigFrame.writeUInt16LE(6, 1);  // signal_id = 6
        sigFrame.writeInt32LE(Math.floor(tick / 4), 3);  // value = seconds
        client.send(sigFrame, 0, 7, UDP_PORT, '127.0.0.1');
    }

    // Signal 2 (score) — increment every 10 ticks
    if (tick % 40 === 0) {
        const sigFrame = Buffer.alloc(7);
        sigFrame[0] = 0x20;
        sigFrame.writeUInt16LE(2, 1);  // signal_id = 2 (score)
        sigFrame.writeInt32LE(Math.floor(tick / 40), 3);
        client.send(sigFrame, 0, 7, UDP_PORT, '127.0.0.1');
        console.log(`[Hub] Score → ${Math.floor(tick / 40)}`);
    }

    // Batch update: signals 0,1 (head position) every 250ms
    if (tick % 1 === 0) {
        const batchFrame = Buffer.alloc(3 + 2 * 6);  // 2 entries
        batchFrame[0] = 0x21;  // DS_NOW_SIG_BATCH
        batchFrame[1] = 2;     // count
        batchFrame[2] = tick & 0xFF;  // seq

        // Signal 0 (headX)
        batchFrame.writeUInt16LE(0, 3);
        batchFrame.writeInt32LE(4 + (tick % 8), 5);

        // Signal 1 (headY)
        batchFrame.writeUInt16LE(1, 9);
        batchFrame.writeInt32LE(4, 11);

        client.send(batchFrame, 0, batchFrame.length, UDP_PORT, '127.0.0.1');
    }
}, 250);

// ─── Listen for events from panel/browser ───
const listener = dgram.createSocket('udp4');
// Note: relay bridge sends events back to the source address,
// so we'd need to be listening on the same port. For testing,
// the relay bridge console logs will show events.

console.log('[Hub] Sending signals every 250ms...');
console.log('[Hub] Press Ctrl+C to stop');
