#!/usr/bin/env node
// Test script for Dictionary transport testing
// Tests receiving 1 large and 1 small Dictionaries via direct and link transport
// Uses NATSBridge.js smartreceive with "dictionary" type

const { smartreceive, log_trace } = require('./src/NATSBridge');

// Configuration
const SUBJECT = "/NATSBridge_dict_test";
const NATS_URL = "nats.yiem.cc";

// Helper: Log with correlation ID
function log_trace(message) {
    const timestamp = new Date().toISOString();
    console.log(`[${timestamp}] ${message}`);
}

// Receiver: Listen for messages and verify Dictionary handling
async function test_dict_receive() {
    // Connect to NATS
    const { connect } = require('nats');
    const nc = await connect({ servers: [NATS_URL] });
    
    // Subscribe to the subject
    const sub = nc.subscribe(SUBJECT);
    
    for await (const msg of sub) {
        log_trace(`Received message on ${msg.subject}`);
        
        // Use NATSBridge.smartreceive to handle the data
        const result = await smartreceive(
            msg,
            {
                maxRetries: 5,
                baseDelay: 100,
                maxDelay: 5000
            }
        );
        
        // Result is an envelope dictionary with payloads field
        // Access payloads with result.payloads
        for (const { dataname, data, type } of result.payloads) {
            if (typeof data === 'object' && data !== null && !Array.isArray(data)) {
                log_trace(`Received Dictionary '${dataname}' of type ${type}`);
                
                // Display dictionary contents
                console.log("  Contents:");
                for (const [key, value] of Object.entries(data)) {
                    console.log(`    ${key} => ${value}`);
                }
                
                // Save to JSON file
                const fs = require('fs');
                const output_path = `./received_${dataname}.json`;
                const json_str = JSON.stringify(data, null, 2);
                fs.writeFileSync(output_path, json_str);
                log_trace(`Saved Dictionary to ${output_path}`);
            } else {
                log_trace(`Received unexpected data type for '${dataname}': ${typeof data}`);
            }
        }
    }
    
    // Keep listening for 10 seconds
    setTimeout(() => {
        nc.close();
        process.exit(0);
    }, 120000);
}

// Run the test
console.log("Starting Dictionary transport test...");
console.log("Note: This receiver will wait for messages from the sender.");
console.log("Run test_js_to_js_dict_sender.js first to send test data.");

// Run receiver
console.log("testing smartreceive");
test_dict_receive();

console.log("Test completed.");