#!/usr/bin/env julia
# Test script for text transport testing
# Tests receiving 1 large and 1 small text from Julia serviceA to Julia serviceB
# Uses NATSBridge.jl smartreceive with "text" type

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

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

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


# ------------------------------------------------------------------------------------------------ #
#                                        test text transfer                                        #
# ------------------------------------------------------------------------------------------------ #


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


# Receiver: Listen for messages and verify text handling
function test_text_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, String)
                log_trace("Received text '$dataname' of type $data_type")
                log_trace("  Length: $(length(data)) characters")
                
                # Display first 100 characters
                if length(data) > 100
                    log_trace("  First 100 characters: $(data[1:100])...")
                else
                    log_trace("  Content: $data")
                end
                
                # Save to file
                output_path = "./received_$dataname.txt"
                write(output_path, data)
                log_trace("Saved text 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 text transport test...")
println("Note: This receiver will wait for messages from the sender.")
println("Run test_julia_to_julia_text_sender.jl first to send test data.")

# Run receiver
println("testing smartreceive for text")
test_text_receive()

println("Test completed.")