#!/bin/bash
# fix_docs.sh - Post-processing script to fix .NET client documentation

set -e

echo "🔧 Fixing .NET client documentation..."

DOCS_DIR="docs"

# Function to fix MemoriesApi.md documentation
fix_memories_api_docs() {
    local docs_file="${DOCS_DIR}/MemoriesApi.md"

    if [ ! -f "$docs_file" ]; then
        echo "⚠️  $docs_file not found, skipping documentation fixes"
        return
    fi

    echo "📝 Fixing retrieve_memory documentation in $docs_file"

    # Create temporary file with fixed documentation
    cat > /tmp/retrieve_memory_section.md << 'RETRIEVE_MEMORY_EOF'
# **RetrieveMemory**
> 📡 **Stream Semantic Memory Retrieval**

Use the `StreamingClient` class for streaming memory retrieval:

### Working Example with Streaming Client

```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
await foreach (var ev in streamingClient.RetrieveMemoryStreamChatAsync(
    "your search query",                              // message
    new List<string> { "550e8400-e29b-41d4-a716-446655440000" },  // space IDs
    10,                                                // requested size
    true,                                              // fetch memory
    false,                                             // fetch memory content
    "ndjson",                                          // format (ndjson or sse)
    "550e8400-e29b-41d4-a716-446655440001",           // LLM ID
    "550e8400-e29b-41d4-a716-446655440000",           // 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}");
    }
}
```

### Parameters

Same parameters as the standard method, with additional ChatPostProcessor parameters:
- `ppLlmId`: UUID of LLM for abstract generation
- `ppRerankerId`: UUID of reranker for result reranking
- `ppRelevanceThreshold`: Minimum relevance score
- `ppLlmTemp`: LLM temperature for generation
- `ppMaxResults`: Maximum results to return
- `ppChronologicalResort`: Whether to resort by creation time
- `format`: Streaming format (`"ndjson"` or `"sse"`)

### Return type

IAsyncEnumerable<StreamingEvent> - Async stream of memory retrieval events

### Authorization

[ApiKeyAuth](../README.md#ApiKeyAuth)

RETRIEVE_MEMORY_EOF

    # Create temporary file for advanced retrieve
    cat > /tmp/retrieve_memory_advanced_section.md << 'RETRIEVE_ADVANCED_EOF'
# **RetrieveMemoryAdvanced**
> 📡 **Advanced Stream Semantic Memory Retrieval**

Use the `StreamingClient` class for advanced streaming memory retrieval with custom post-processor configuration:

### Working Example with Streaming Client

```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);

// Create advanced request with custom post-processor
var request = new AdvancedMemoryStreamRequest
{
    Message = "your search query",
    SpaceIds = new List<string> { "550e8400-e29b-41d4-a716-446655440000" },
    RequestedSize = 10,
    FetchMemory = true,
    FetchMemoryContent = false,
    Format = "ndjson",  // or "sse"
    PostProcessorName = "com.goodmem.retrieval.postprocess.ChatPostProcessorFactory",
    PostProcessorConfig = new Dictionary<string, object>
    {
        ["llm_id"] = "550e8400-e29b-41d4-a716-446655440001",
        ["reranker_id"] = "550e8400-e29b-41d4-a716-446655440000",
        ["relevance_threshold"] = 0.5,
        ["llm_temp"] = 0.3,
        ["max_results"] = 10,
        ["chronological_resort"] = true
    }
};

// Execute advanced 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 item: {ev.RetrievedItem}");
    }
}
```

### Parameters

Use `AdvancedMemoryStreamRequest` with:
- `Message`: Query message
- `SpaceIds`: List of space UUIDs
- `RequestedSize`: Maximum memories to retrieve
- `FetchMemory`: Whether to fetch memory definitions
- `FetchMemoryContent`: Whether to fetch original content
- `Format`: Streaming format (`"ndjson"` or `"sse"`)
- `PostProcessorName`: Name of custom post-processor
- `PostProcessorConfig`: Configuration dictionary for the post-processor

### Return type

IAsyncEnumerable<StreamingEvent> - Async stream of memory retrieval events

### Authorization

[ApiKeyAuth](../README.md#ApiKeyAuth)

RETRIEVE_ADVANCED_EOF

    # Use Python to do the replacement
    python3 << 'PYTHON_EOF'
import re

# Read the original file
with open('docs/MemoriesApi.md', 'r') as f:
    content = f.read()

# Read the replacement sections
with open('/tmp/retrieve_memory_section.md', 'r') as f:
    retrieve_memory_section = f.read()

with open('/tmp/retrieve_memory_advanced_section.md', 'r') as f:
    retrieve_memory_advanced_section = f.read()

# Replace retrieveMemory section (match either with or without anchor tag)
content = re.sub(
    r'(<a id="[^"]*retrievememory[^"]*"></a>\n)?# \*\*RetrieveMemory\*\*.*?(?=\n(<a id="|# \*\*)|$)',
    retrieve_memory_section,
    content,
    flags=re.DOTALL
)

# Replace retrieveMemoryAdvanced section (match either with or without anchor tag)
content = re.sub(
    r'(<a id="[^"]*retrievememoryadvanced[^"]*"></a>\n)?# \*\*RetrieveMemoryAdvanced\*\*.*?(?=\n(<a id="|# \*\*)|$)',
    retrieve_memory_advanced_section,
    content,
    flags=re.DOTALL
)

# Write back
with open('docs/MemoriesApi.md', 'w') as f:
    f.write(content)

print("✅ Updated MemoriesApi.md with StreamingClient examples")
PYTHON_EOF

    # Clean up temporary files
    rm -f /tmp/retrieve_memory_section.md /tmp/retrieve_memory_advanced_section.md
}

# Main execution
if [ -d "$DOCS_DIR" ]; then
    fix_memories_api_docs
    echo "✅ Documentation fixes applied successfully"
else
    echo "⚠️  docs/ directory not found, skipping documentation fixes"
fi