#!/usr/bin/env python3
"""
Conversation Bridge - Automatic Conversation Indexing
=====================================================

This module provides automatic indexing and processing of new conversations to keep
the memory system continuously updated. It monitors conversation files and intelligently
extracts meaningful content for memory storage and search.

Purpose:
    - Automatically index new conversations as they occur
    - Extract meaningful content from conversation files
    - Keep memory system synchronized with latest interactions
    - Provide periodic batch processing for conversation data
    - Bridge between conversation storage and memory systems

Architecture:
    - Conversation file monitoring and processing
    - Content extraction and filtering logic
    - Integration with MemoryInterface for storage
    - Time-based indexing with configurable windows
    - Intelligent content relevance filtering

Key Features:
    - Automatic conversation discovery
    - Time-window based processing (configurable hours)
    - Content quality filtering (minimum length, relevance)
    - Metadata preservation and enhancement
    - Integration with centralized memory system
    - Batch processing for efficiency

Usage:
    ```python
    from conversations.conversation_bridge import index_recent_conversations
    
    # Index conversations from last 24 hours
    index_recent_conversations(hours_back=24)
    
    # Custom time window
    index_recent_conversations(hours_back=6)
    ```

Content Processing:
    - Filters messages by type (user, assistant)
    - Applies minimum content length thresholds
    - Preserves conversation metadata
    - Extracts timestamps and context
    - Categorizes content appropriately

Data Flow:
    1. Scan conversation directories
    2. Filter by modification time
    3. Parse JSONL conversation files
    4. Extract meaningful messages
    5. Apply content quality filters
    6. Store in memory system with metadata

Scheduling:
    - Designed for periodic execution
    - Can be run via cron jobs or scheduled tasks
    - Supports both incremental and full indexing
    - Configurable time windows for processing

Author: MIRA Memory System
Version: 2.1 (Enhanced Documentation)
"""

from pathlib import Path
from datetime import datetime, timedelta
import json
from interfaces.interface import MemoryInterface

# Import centralized config
from config import MEMORY_DIR
# Import intelligent Claude path discovery
from utils.claude_path_discovery import get_claude_conversations_path

def index_recent_conversations(hours_back=24):
    """Index conversations from the last N hours"""
    
    memory = MemoryInterface()
    memory.initialize()
    
    # Use intelligent path discovery instead of hardcoded path
    claude_base_path = get_claude_conversations_path()
    if not claude_base_path:
        print("⚠️ Claude Code conversation files not found")
        print("💡 Run 'mira setup' to configure conversation paths")
        return
    
    # For now, process all projects - in future versions could be more selective
    claude_dir = claude_base_path
    if not claude_dir.exists():
        print(f"⚠️ Claude conversation directory not accessible: {claude_dir}")
        return
    
    cutoff = datetime.now() - timedelta(hours=hours_back)
    indexed = 0
    
    for conv_file in claude_dir.glob("*.jsonl"):
        if datetime.fromtimestamp(conv_file.stat().st_mtime) < cutoff:
            continue
            
        with open(conv_file, 'r') as f:
            for line in f:
                try:
                    msg = json.loads(line.strip())
                    
                    # Extract meaningful content
                    if msg.get('type') in ['user', 'assistant']:
                        content = msg.get('content', '')
                        if len(content) > 50:  # Skip trivial messages
                            # Store in memory
                            memory.remember(
                                content[:1000],  # Limit size
                                importance=0.5,
                                metadata={
                                    'category': "conversation",
                                    'file': conv_file.name,
                                    'timestamp': msg.get('timestamp', ''),
                                    'type': msg.get('type')
                                }
                            )
                            indexed += 1
                except:
                    pass
    
    memory.save()
    print(f"Indexed {indexed} conversation entries")

if __name__ == "__main__":
    index_recent_conversations()
