#!/usr/bin/env julia
# Test script for large payload testing using binary transport
# Tests sending a large file (> 1MB) via smartsend with binary type
# Updated to match NATSBridge.jl API

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


# workdir = 

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

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



# ------------------------------------------------------------------------------------------------ #
#                                        test file transfer                                        #
# ------------------------------------------------------------------------------------------------ #

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

# Receiver: Listen for messages and verify large payload handling
function test_large_binary_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"]
            # Check transport type from the envelope
            # For link transport, data is the URL string
            # For direct transport, data is the actual payload bytes
            
            if isa(data, Vector{UInt8})
                file_size = length(data)
                log_trace("Received $(file_size) bytes of binary data for '$dataname' of type $data_type")
                
                # Save received data to a test file
                output_path = "./new_$dataname"
                write(output_path, data)
                log_trace("Saved received data to $output_path")
            else
                log_trace("Received $(file_size) bytes of binary data for '$dataname' of type $data_type")
            end
        end
    end
    
    # Keep listening for 10 seconds
    sleep(120)  
    NATS.drain(conn)
end


# Run the test
println("Starting large binary payload test...")

# # Run sender first
# println("start smartsend")
# test_large_binary_send()

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

println("Test completed.")