#!/usr/bin/env python3
"""
Test script for file transport testing - Micropython
Tests sending binary files via NATS using nats_bridge.py smartsend
"""

import sys
import os

# Add src to path for import
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from nats_bridge import smartsend, log_trace
import uuid

# Configuration
SUBJECT = "/NATSBridge_file_test"
NATS_URL = "nats://nats.yiem.cc:4222"
FILESERVER_URL = "http://192.168.88.104:8080"
SIZE_THRESHOLD = 1_000_000  # 1MB

# Create correlation ID for tracing
correlation_id = str(uuid.uuid4())


def main():
    # Create small binary data (will use direct transport)
    small_binary = b"This is small binary data for testing direct transport."
    small_binary += b"\x00" * 100  # Add some null bytes
    
    # Create large binary data (will use link transport if > 1MB)
    # Generate a larger binary (~2MB to ensure link transport)
    large_binary = bytes([
        (i * 7) % 256 for i in range(2_000_000)
    ])
    
    # Test data 1: small binary (direct transport)
    data1 = ("small_binary", small_binary, "binary")
    
    # Test data 2: large binary (link transport)
    data2 = ("large_binary", large_binary, "binary")
    
    log_trace(correlation_id, f"Starting smartsend for subject: {SUBJECT}")
    log_trace(correlation_id, f"Correlation ID: {correlation_id}")
    
    # Use smartsend with binary type
    env, env_json_str = smartsend(
        SUBJECT,
        [data1, data2],  # List of (dataname, data, type) tuples
        nats_url=NATS_URL,
        fileserver_url=FILESERVER_URL,
        size_threshold=SIZE_THRESHOLD,
        correlation_id=correlation_id,
        msg_purpose="chat",
        sender_name="file_sender",
        receiver_name="",
        receiver_id="",
        reply_to="",
        reply_to_msg_id="",
        is_publish=True  # Publish the message to NATS
    )
    
    log_trace(correlation_id, f"Sent message with {len(env.payloads)} payloads")
    
    # Log transport type for each payload
    for i, payload in enumerate(env.payloads):
        log_trace(correlation_id, f"Payload {i+1} ('{payload.dataname}'):")
        log_trace(correlation_id, f"  Transport: {payload.transport}")
        log_trace(correlation_id, f"  Type: {payload.type}")
        log_trace(correlation_id, f"  Size: {payload.size} bytes")
        log_trace(correlation_id, f"  Encoding: {payload.encoding}")
        
        if payload.transport == "link":
            log_trace(correlation_id, f"  URL: {payload.data}")
    
    print(f"Test completed. Correlation ID: {correlation_id}")


if __name__ == "__main__":
    main()