#!/usr/bin/env python3
"""
Example usage of the memory_search module.

Make sure to set your environment variables before running:
export NEO4J_URI="neo4j://127.0.0.1:7687"
export NEO4J_USER="neo4j"
export NEO4J_PASSWORD="your_password"
export OPENAI_API_KEY="your_openai_api_key"
export MODEL_NAME="gpt-4o"
"""

import asyncio
import json
from memory_search import MemorySearcher, search_memory_facts, search_memory_comprehensive


async def example_search_facts():
    """Example: Search for facts only."""
    print("🔍 Searching for facts about 'user authentication'...")
    facts = await search_memory_facts("user authentication", max_results=5)
    
    if facts:
        print(f"✅ Found {len(facts)} facts:")
        for i, fact in enumerate(facts, 1):
            print(f"\n--- Fact {i} ---")
            print(f"Fact: {fact.get('fact', 'N/A')}")
            print(f"Source: {fact.get('source_node_name', 'N/A')}")
            print(f"Target: {fact.get('target_node_name', 'N/A')}")
            print(f"Created: {fact.get('created_at', 'N/A')}")
    else:
        print("❌ No facts found.")


async def example_comprehensive_search():
    """Example: Comprehensive search (facts, entities, conversations)."""
    print("\n🔍 Comprehensive search for 'project status'...")
    results = await search_memory_comprehensive("project status", max_results=5)
    
    if "error" in results:
        print(f"❌ Error: {results['error']}")
        return
    
    # Display facts
    if "facts" in results and results["facts"]:
        print(f"\n📋 Found {len(results['facts'])} facts:")
        for i, fact in enumerate(results["facts"], 1):
            print(f"  {i}. {fact.get('fact', 'N/A')}")
    
    # Display entities
    if "entities" in results and results["entities"]:
        print(f"\n👥 Found {len(results['entities'])} entities:")
        for i, entity in enumerate(results["entities"], 1):
            print(f"  {i}. {entity.get('name', 'N/A')} ({entity.get('group_id', 'N/A')})")
    
    # Display conversations
    if "conversations" in results and results["conversations"]:
        print(f"\n💬 Found {len(results['conversations'])} conversations:")
        for i, conv in enumerate(results["conversations"], 1):
            content = conv.get('content', 'N/A')
            # Truncate long content
            if len(content) > 100:
                content = content[:100] + "..."
            print(f"  {i}. {content}")


async def example_advanced_search():
    """Example: Using MemorySearcher class directly for more control."""
    print("\n🔍 Advanced search with MemorySearcher class...")
    
    searcher = MemorySearcher()
    
    # Search for facts with specific parameters
    facts = await searcher.search_facts(
        query="deployment process",
        max_results=3,
        # group_ids=["specific_group_id"],  # Uncomment if you have specific group IDs
        # center_around="node_uuid"          # Uncomment if you want to center around a specific node
    )
    
    if facts:
        print(f"✅ Found {len(facts)} facts about deployment:")
        for fact in facts:
            print(f"  • {fact.get('fact', 'N/A')}")
    else:
        print("❌ No facts found about deployment.")


async def main():
    """Run all examples."""
    print("🚀 Memory Search Examples")
    print("=" * 50)
    
    try:
        await example_search_facts()
        await example_comprehensive_search()
        await example_advanced_search()
        
        print("\n✅ All examples completed successfully!")
        
    except Exception as e:
        print(f"\n❌ Error running examples: {e}")
        print("Make sure your environment variables are set correctly:")
        print("- NEO4J_URI")
        print("- NEO4J_USER") 
        print("- NEO4J_PASSWORD")
        print("- OPENAI_API_KEY")
        print("- MODEL_NAME (optional, defaults to gpt-4o)")


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