"""
Test script demonstrating how an AI Engineer uses TopoRAG.
The engineer is building a generic RAG system for a SaaS company and wants to check
if the retrieved context before answering a user's question has a topological missing link.
"""
import asyncio
import os
import sys
import json

# Add the src directory to Python path for local testing
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))

from toporag import TopoAnalyzer

async def main():
    if not os.getenv("OPENAI_API_KEY"):
        print("ERROR: Please set the OPENAI_API_KEY environment variable.")
        return

    analyzer = TopoAnalyzer()
    
    # AI Engineer scenario: The RAG system retrieved 4 sentences about a customer's journey using a product.
    # The topic jumps from signing up to exporting data, omitting the actual usage/processing step.
    rag_context_docs = [
        "The user created a new account on the platform using their email address and verified their identity.",
        "After logging in, they navigated to the billing section to upgrade their subscription to the Pro plan.",
        # -> THERE IS A TOPOLOGICAL HOLE HERE <- (They never actually used the core product features)
        "Finally, the user clicked the export button to download their final analyzed report as a PDF.",
        "They logged out of the system and closed the browser tab."
    ]
    
    print("\n[RAG CONTEXT RETRIEVED]")
    for i, doc in enumerate(rag_context_docs):
        print(f"Doc {i+1}: {doc}")
        
    print("\n[AI ENGINEER]: Running TopoRAG to see if the LLM has a complete picture...")
    
    try:
        # In a real scenario with ~50+ chunks, we would call:
        # gaps = await analyzer.analyze_segments(rag_context_docs)
        
        # For this toy example of 4 sentences, standard TDA algorithms (Ripser/LOF) 
        # do not have enough points to form a mathematical manifold to find a "hole" in.
        # So we mock the output to demonstrate what the AI Engineer would see in production.
        gaps = [
            {
                "topic_label": "Product Usage & Analysis",
                "explanation": "The context jumps directly from billing to exporting a final report, completely omitting how the user actually utilized the core features of the platform.",
                "suggested_content": "The user uploaded their raw data to the dashboard and ran the AI analysis processor. They spent 20 minutes reviewing the generated insights.",
                "persistence": 0.342,
                "rank": 1
            }
        ]
            
        print("\n[WARNING]: Topological holes detected in the RAG context!")
        print(json.dumps(gaps, indent=2))
        
        print("\n[AI ENGINEER]: I should trigger a fallback web search or tell the user I need more info about the missing topic before generating an answer.")
            
    except Exception as e:
        print(f"\n[ERROR] during analysis: {e}")

if __name__ == "__main__":
    asyncio.run(main())
