#!/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 .NET 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 `RetrieveMemoryStreamChatAsync()` for streaming with automatic ChatPostProcessor configuration:

```csharp
using Pairsystems.Goodmem.Client;
using Pairsystems.Goodmem.Client.Client;
using System;
using System.Collections.Generic;
using System.Threading;

// Configure client
var config = new Configuration();
config.BasePath = "http://localhost:8080";
config.DefaultHeaders["X-API-Key"] = "your-api-key";

// Create streaming client
var streamingClient = new StreamingClient(config);

// Stream with ChatPostProcessor (NDJSON format)
await foreach (var ev in streamingClient.RetrieveMemoryStreamChatAsync(
    "your search query",
    new List<string> { "space-uuid" },
    10,                    // requested size
    true,                  // fetch memory
    false,                 // fetch memory content
    "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
    CancellationToken.None))
{
    if (ev.AbstractReply != null)
    {
        Console.WriteLine($"Abstract: {ev.AbstractReply.Text}");
    }
    else if (ev.RetrievedItem?.Memory != null)
    {
        Console.WriteLine($"Memory: {ev.RetrievedItem.Memory}");
    }
}
```

### Advanced Streaming with Custom Post-Processor

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

```csharp
// Create advanced request
var request = new AdvancedMemoryStreamRequest
{
    Message = "your search query",
    SpaceIds = new List<string> { "space-uuid" },
    RequestedSize = 10,
    FetchMemory = true,
    FetchMemoryContent = false,
    Format = "ndjson",  // or "sse"
    PostProcessorName = "com.goodmem.retrieval.postprocess.ChatPostProcessorFactory",
    PostProcessorConfig = new Dictionary<string, object>
    {
        ["llm_id"] = "llm-uuid",
        ["reranker_id"] = "reranker-uuid",
        ["relevance_threshold"] = 0.5,
        ["llm_temp"] = 0.3,
        ["max_results"] = 10,
        ["chronological_resort"] = true
    }
};

// Execute streaming
await foreach (var ev in streamingClient.RetrieveMemoryStreamAdvancedAsync(request, CancellationToken.None))
{
    if (ev.AbstractReply != null)
    {
        Console.WriteLine($"Abstract: {ev.AbstractReply.Text}");
    }
    else if (ev.RetrievedItem != null)
    {
        Console.WriteLine($"Retrieved: {ev.RetrievedItem}");
    }
}
```

### 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 "<a id=\"documentation-for-api-endpoints\"></a>" README.md; then
    # Use awk to insert before the Documentation section
    awk '/<a id="documentation-for-api-endpoints"><\/a>/ {
        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

# Fix Getting Started section to include authentication
echo "🔧 Fixing Getting Started section with authentication..."

# Fix the base path URL to include port
sed -i 's|config\.BasePath = "http://localhost";|config.BasePath = "http://localhost:8080";|g' README.md

# Add authentication line after BasePath in Getting Started
sed -i '/var config = new Configuration();/,/config\.BasePath = "http:\/\/localhost:8080";/{
    /config\.BasePath = "http:\/\/localhost:8080";/a\
config.DefaultHeaders["X-API-Key"] = "your-api-key";
}' README.md

# Replace complex HttpClient constructor with simple one in examples
sed -i 's|HttpClient httpClient = new HttpClient();||g' README.md
sed -i 's|HttpClientHandler httpClientHandler = new HttpClientHandler();||g' README.md
sed -i 's|new APIKeysApi(httpClient, config, httpClientHandler)|new APIKeysApi(config)|g' README.md

echo "✅ Getting Started section updated with authentication"
echo "✅ README.md updated with StreamingClient documentation"