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

set -e

echo "🔧 Fixing Go 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` for streaming memory retrieval:

## Working Example with Streaming Client

```go
package main

import (
    "context"
    "fmt"
    "log"

    goodmem_client "github.com/PAIR-Systems-Inc/goodmem/clients/go"
)

func main() {
    // Configure client
    configuration := goodmem_client.NewConfiguration()
    configuration.Host = "http://localhost:8080"
    configuration.DefaultHeader["X-API-Key"] = "your-api-key"

    apiClient := goodmem_client.NewAPIClient(configuration)
    streamingClient := goodmem_client.NewStreamingClient(apiClient)

    // Helper values
    requestedSize := int32(10)
    fetchMemory := true
    fetchMemoryContent := false
    llmID := "550e8400-e29b-41d4-a716-446655440001"
    rerankerID := "550e8400-e29b-41d4-a716-446655440000"
    relevanceThreshold := 0.5
    llmTemp := 0.3
    maxResults := int32(10)
    chronologicalResort := true

    // Stream with ChatPostProcessor
    ctx := context.Background()
    stream, err := streamingClient.RetrieveMemoryStreamChat(
        ctx,
        "your search query",
        []string{"space-uuid"},
        &requestedSize,
        &fetchMemory,
        &fetchMemoryContent,
        goodmem_client.FormatNDJSON,  // or FormatSSE
        &llmID,
        &rerankerID,
        &relevanceThreshold,
        &llmTemp,
        &maxResults,
        &chronologicalResort,
    )
    if err != nil {
        log.Fatalf("Error: %v", err)
    }

    // Process events
    for event := range stream {
        if event.AbstractReply != nil {
            fmt.Printf("Abstract: %s\n", event.AbstractReply.Text)
        } else if event.RetrievedItem != nil && event.RetrievedItem.Memory != nil {
            fmt.Printf("Memory: %v\n", event.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 (`FormatNDJSON` or `FormatSSE`)

## Return type

MemoryStreamChannel - Channel of streaming 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` for advanced streaming memory retrieval with custom post-processor configuration:

## Working Example with Streaming Client

```go
package main

import (
    "context"
    "fmt"
    "log"

    goodmem_client "github.com/PAIR-Systems-Inc/goodmem/clients/go"
)

func main() {
    // Configure client
    configuration := goodmem_client.NewConfiguration()
    configuration.Host = "http://localhost:8080"
    configuration.DefaultHeader["X-API-Key"] = "your-api-key"

    apiClient := goodmem_client.NewAPIClient(configuration)
    streamingClient := goodmem_client.NewStreamingClient(apiClient)

    // Helper values
    requestedSize := int32(10)
    fetchMemory := true
    fetchMemoryContent := false

    // Create advanced request with custom post-processor
    request := &goodmem_client.AdvancedMemoryStreamRequest{
        Message:   "your search query",
        SpaceIDs:  []string{"space-uuid"},
        RequestedSize: &requestedSize,
        FetchMemory: &fetchMemory,
        FetchMemoryContent: &fetchMemoryContent,
        Format: goodmem_client.FormatNDJSON,  // or FormatSSE
        PostProcessorName: "com.goodmem.retrieval.postprocess.ChatPostProcessorFactory",
        PostProcessorConfig: map[string]interface{}{
            "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
    ctx := context.Background()
    stream, err := streamingClient.RetrieveMemoryStreamAdvanced(ctx, request)
    if err != nil {
        log.Fatalf("Error: %v", err)
    }

    // Process events
    for event := range stream {
        if event.AbstractReply != nil {
            fmt.Printf("Abstract: %s\n", event.AbstractReply.Text)
        } else if event.RetrievedItem != nil {
            fmt.Printf("Retrieved item: %v\n", event.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 (`FormatNDJSON` or `FormatSSE`)
- `PostProcessorName`: Name of custom post-processor
- `PostProcessorConfig`: Configuration map for the post-processor

## Return type

MemoryStreamChannel - Channel of streaming 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
content = re.sub(
    r'# RetrieveMemory\n\n.*?(?=\n# [A-Z]|$)',
    retrieve_memory_section,
    content,
    flags=re.DOTALL
)

# Replace RetrieveMemoryAdvanced section
content = re.sub(
    r'# RetrieveMemoryAdvanced\n\n.*?(?=\n# [A-Z]|$)',
    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