#!/usr/bin/env julia
# Test script for text transport testing
# Tests sending 1 large and 1 small text from Julia serviceA to Julia serviceB
# Uses NATSBridge.jl smartsend 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"

# Create correlation ID for tracing
correlation_id = string(uuid4())


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


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


# File upload handler for plik server
function plik_upload_handler(fileserver_url::String, dataname::String, data::Vector{UInt8})::Dict{String, Any}
    # Get upload ID
    url_getUploadID = "$fileserver_url/upload"
    headers = ["Content-Type" => "application/json"]
    body = """{ "OneShot" : true }"""
    httpResponse = HTTP.request("POST", url_getUploadID, headers, body; body_is_form=false)
    responseJson = JSON.parse(String(httpResponse.body))
    uploadid = responseJson["id"]
    uploadtoken = responseJson["uploadToken"]
    
    # Upload file
    file_multipart = HTTP.Multipart(dataname, IOBuffer(data), "application/octet-stream")
    url_upload = "$fileserver_url/file/$uploadid"
    headers = ["X-UploadToken" => uploadtoken]
    
    form = HTTP.Form(Dict("file" => file_multipart))
    httpResponse = HTTP.post(url_upload, headers, form)
    responseJson = JSON.parse(String(httpResponse.body))
    
    fileid = responseJson["id"]
    url = "$fileserver_url/file/$uploadid/$fileid/$dataname"
    
    return Dict("status" => httpResponse.status, "uploadid" => uploadid, "fileid" => fileid, "url" => url)
end


# Sender: Send text via smartsend
function test_text_send()
    # Create a small text (will use direct transport)
    small_text = "Hello, this is a small text message. Testing direct transport via NATS."
    
    # Create a large text (will use link transport if > 1MB)
    # Generate a larger text (~2MB to ensure link transport)
    large_text = join(["Line $i: This is a sample text line with some content to pad the size. " for i in 1:50000], "")
    
    # Test data 1: small text
    data1 = ("small_text", small_text, "text")
    
    # Test data 2: large text
    data2 = ("large_text", large_text, "text")
    
    # Use smartsend with text type
    # For small text: will use direct transport (Base64 encoded UTF-8)
    # For large text: will use link transport (uploaded to fileserver)
    env = NATSBridge.smartsend(
        SUBJECT,
        [data1, data2];  # List of (dataname, data, type) tuples
        nats_url = NATS_URL,
        fileserver_url = FILESERVER_URL,
        fileserverUploadHandler = plik_upload_handler,
        size_threshold = 1_000_000,  # 1MB threshold
        correlation_id = correlation_id,
        msg_purpose = "chat",
        sender_name = "text_sender",
        receiver_name = "",
        receiver_id = "",
        reply_to = "",
        reply_to_msg_id = ""
    )
    
    log_trace("Sent message with $(length(env.payloads)) payloads")
    
    # Log transport type for each payload
    for (i, payload) in enumerate(env.payloads)
        log_trace("Payload $i ('$payload.dataname'):")
        log_trace("  Transport: $(payload.transport)")
        log_trace("  Type: $(payload.type)")
        log_trace("  Size: $(payload.size) bytes")
        log_trace("  Encoding: $(payload.encoding)")
        
        if payload.transport == "link"
            log_trace("  URL: $(payload.data)")
        end
    end
end


# Run the test
println("Starting text transport test...")
println("Correlation ID: $correlation_id")

# Run sender
println("start smartsend for text")
test_text_send()

println("Test completed.")