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

using NATS, JSON, UUIDs, Dates, PrettyPrinting, DataFrames, Arrow, HTTP

# Include the bridge module
include("../src/NATSBridge.jl")
using .NATSBridge

# Configuration
const SUBJECT = "/NATSBridge_dict_test"
const NATS_URL = "nats.yiem.cc"
const FILESERVER_URL = "http://192.168.88.104:8080"


# ------------------------------------------------------------------------------------------------ #
#                                        test dictionary transfer                                  #
# ------------------------------------------------------------------------------------------------ #


# Helper: Log with correlation ID
function log_trace(message)
    timestamp = Dates.now()
    println("[$timestamp] $message")
end


# Receiver: Listen for messages and verify Dictionary handling
function test_dict_receive()
    conn = NATS.connect(NATS_URL)
    NATS.subscribe(conn, SUBJECT) do msg
        log_trace("Received message on $(msg.subject)")
        
        # Use NATSBridge.smartreceive to handle the data
        # API: smartreceive(msg, download_handler; max_retries, base_delay, max_delay)
        result = NATSBridge.smartreceive(
            msg;
            max_retries = 5,
            base_delay = 100,
            max_delay = 5000
        )
        
        # Result is an envelope dictionary with payloads field containing list of (dataname, data, data_type) tuples
        for (dataname, data, data_type) in result["payloads"]
            if isa(data, JSON.Object{String, Any})
                log_trace("Received Dictionary '$dataname' of type $data_type")
                
                # Display dictionary contents
                println("  Contents:")
                for (key, value) in data
                    println("    $key => $value")
                end
                
                # Save to JSON file
                output_path = "./received_$dataname.json"
                json_str = JSON.json(data, 2)
                write(output_path, json_str)
                log_trace("Saved Dictionary to $output_path")
            else
                log_trace("Received unexpected data type for '$dataname': $(typeof(data))")
            end
        end
    end
    
    # Keep listening for 10 seconds
    sleep(120)  
    NATS.drain(conn)
end


# Run the test
println("Starting Dictionary transport test...")
println("Note: This receiver will wait for messages from the sender.")
println("Run test_julia_to_julia_dict_sender.jl first to send test data.")

# Run receiver
println("testing smartreceive")
test_dict_receive()

println("Test completed.")