#!/bin/bash
# fix_readme.sh - Add streaming client documentation to README.md

set -e

echo "🔧 Adding StreamingClient documentation to README.md..."

if [ ! -f "README.md" ]; then
    echo "⚠️  README.md not found, skipping"
    exit 0
fi

# Check if streaming section already exists
if grep -q "## Streaming Memory Retrieval" README.md; then
    echo "ℹ️  Streaming section already exists in README.md"
    exit 0
fi

# Create the streaming documentation section
cat > /tmp/streaming_section.md << 'STREAMING_EOF'

## Streaming Memory Retrieval

The GoodMem Java client provides a `StreamingClient` class for real-time streaming memory retrieval. This is the **recommended approach** for memory retrieval operations.

### Supported Formats

The StreamingClient supports two streaming formats:

- **NDJSON** (`application/x-ndjson`) - Newline-delimited JSON (default, recommended)
- **SSE** (`text/event-stream`) - Server-Sent Events

### Basic Streaming with ChatPostProcessor

Use `retrieveMemoryStreamChat()` for streaming with automatic ChatPostProcessor configuration:

```java
import ai.pairsys.goodmem.client.ApiClient;
import ai.pairsys.goodmem.client.StreamingClient;
import ai.pairsys.goodmem.client.StreamingClient.*;

import java.util.List;
import java.util.stream.Stream;

// Configure client
ApiClient apiClient = new ApiClient();
apiClient.setBasePath("http://localhost:8080");
apiClient.setApiKey("your-api-key");

// Create streaming client
StreamingClient streamingClient = new StreamingClient(apiClient);

// Stream with ChatPostProcessor (NDJSON format)
Stream<MemoryStreamResponse> stream = streamingClient.retrieveMemoryStreamChat(
    "your search query",
    List.of("space-uuid"),
    10,                                           // requested size
    true,                                         // fetch memory
    false,                                        // fetch memory content
    StreamingFormat.NDJSON,                       // format (NDJSON or SSE)
    "llm-uuid",                                   // LLM ID
    "reranker-uuid",                              // reranker ID
    0.5,                                          // relevance threshold
    0.3,                                          // LLM temperature
    10,                                           // max results
    true                                          // chronological resort
);

// Process events
stream.forEach(event -> {
    if (event.getAbstractReply() != null) {
        System.out.println("Abstract: " + event.getAbstractReply().getText());
    } else if (event.getRetrievedItem() != null
            && event.getRetrievedItem().getMemory() != null) {
        System.out.println("Memory: " + event.getRetrievedItem().getMemory());
    }
});
```

### Advanced Streaming with Custom Post-Processor

Use `retrieveMemoryStreamAdvanced()` for custom post-processor configuration:

```java
import java.util.HashMap;
import java.util.Map;

// Create advanced request
AdvancedMemoryStreamRequest request = new AdvancedMemoryStreamRequest(
    "your search query",
    List.of("space-uuid")
);
request.setRequestedSize(10);
request.setFetchMemory(true);
request.setFormat(StreamingFormat.NDJSON);  // or StreamingFormat.SSE

// Configure custom post-processor
request.setPostProcessorName("com.goodmem.retrieval.postprocess.ChatPostProcessorFactory");

Map<String, Object> config = new HashMap<>();
config.put("llm_id", "llm-uuid");
config.put("reranker_id", "reranker-uuid");
config.put("relevance_threshold", 0.5);
config.put("llm_temp", 0.3);
config.put("max_results", 10);
config.put("chronological_resort", true);
request.setPostProcessorConfig(config);

// Execute streaming
Stream<MemoryStreamResponse> stream = streamingClient.retrieveMemoryStreamAdvanced(request);

// Process events
stream.forEach(event -> {
    if (event.getAbstractReply() != null) {
        System.out.println("Abstract: " + event.getAbstractReply().getText());
    } else if (event.getRetrievedItem() != null) {
        System.out.println("Retrieved: " + event.getRetrievedItem());
    }
});
```

### Choosing Between NDJSON and SSE

- **NDJSON** (recommended): Simpler parsing, better for most use cases
- **SSE**: Standard browser EventSource API compatible, useful for web applications

STREAMING_EOF

# Insert the streaming section before "## Documentation for API Endpoints"
if grep -q "## Documentation for API Endpoints" README.md; then
    # Use awk to insert before the Documentation section
    awk '/## Documentation for API Endpoints/ {
        while ((getline line < "/tmp/streaming_section.md") > 0) {
            print line
        }
        print ""
    }
    {print}' README.md > README.md.tmp
    mv README.md.tmp README.md
    echo "✅ Added streaming documentation to README.md"
else
    # Append at the end if section not found
    cat /tmp/streaming_section.md >> README.md
    echo "✅ Appended streaming documentation to README.md"
fi

# Clean up
rm -f /tmp/streaming_section.md

echo "✅ README.md updated with StreamingClient documentation"