#!/bin/bash
# fix_docs.sh - Post-processing script to fix Java client documentation
# Similar to Python's fix_setup.py, this adds proper StreamingClient examples

set -e

echo "🔧 Fixing Java 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

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

public class BasicStreamingExample {
    public static void main(String[] args) throws StreamError {
        // 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 memory retrieval results with ChatPostProcessor
        Stream<MemoryStreamResponse> stream = streamingClient.retrieveMemoryStreamChat(
            "your search query",                              // message
            List.of("550e8400-e29b-41d4-a716-446655440000"),  // space IDs
            10,                                                // requested size
            true,                                              // fetch memory
            false,                                             // fetch memory content
            "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
        );

        // Process streaming 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());
            }
        });
    }
}
```

### 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

### Return type

`Stream<MemoryStreamResponse>` - 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

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

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

public class AdvancedStreamingExample {
    public static void main(String[] args) throws StreamError {
        // Configure client
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("http://localhost:8080");
        apiClient.setApiKey("your-api-key");

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

        // Create advanced request with custom post-processor
        AdvancedMemoryStreamRequest request = new AdvancedMemoryStreamRequest(
            "your search query",
            List.of("550e8400-e29b-41d4-a716-446655440000")
        );
        request.setRequestedSize(10);
        request.setFetchMemory(true);
        request.setFetchMemoryContent(false);

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

        Map<String, Object> postProcessorConfig = new HashMap<>();
        postProcessorConfig.put("llm_id", "550e8400-e29b-41d4-a716-446655440001");
        postProcessorConfig.put("reranker_id", "550e8400-e29b-41d4-a716-446655440000");
        postProcessorConfig.put("relevance_threshold", 0.5);
        postProcessorConfig.put("llm_temp", 0.3);
        postProcessorConfig.put("max_results", 10);
        postProcessorConfig.put("chronological_resort", true);
        request.setPostProcessorConfig(postProcessorConfig);

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

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

### 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
- `postProcessorName`: Name of custom post-processor
- `postProcessorConfig`: Configuration map for the post-processor

### Return type

`Stream<MemoryStreamResponse>` - Stream of memory retrieval events

### Authorization

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

RETRIEVE_ADVANCED_EOF

    # Use Python to do the replacement (more reliable than sed for multiline)
    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 retrieve_memory section
content = re.sub(
    r'# \*\*retrieveMemory\*\*.*?(?=\n# \*\*|$)',
    retrieve_memory_section,
    content,
    flags=re.DOTALL
)

# Replace retrieve_memory_advanced section
content = re.sub(
    r'# \*\*retrieveMemoryAdvanced\*\*.*?(?=\n# \*\*|$)',
    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