"""
ChromaDB Compatibility Layer

Fixes compatibility issues between ChromaDB 0.3.29 and MCP server
by providing missing abstract method implementations.
"""

import chromadb
from chromadb.config import Settings
from typing import Optional, Dict, Any, List
import sqlite3
import os
from pathlib import Path


class ChromaDBCompatibilityPatch:
    """Patches ChromaDB for compatibility with MCP server."""
    
    @staticmethod
    def patch_chromadb():
        """Apply compatibility patches to ChromaDB 0.3.29."""
        try:
            # Import the problematic module
            from chromadb.segment.impl.metadata import sqlite
            
            # Check if SqliteMetadataSegment exists and needs patching
            if hasattr(sqlite, 'SqliteMetadataSegment'):
                original_class = sqlite.SqliteMetadataSegment
                
                # Create a patched version with the missing delete method
                class PatchedSqliteMetadataSegment(original_class):
                    def delete(self, ids: List[str]) -> None:
                        """Delete metadata for given IDs."""
                        if not ids:
                            return
                        
                        # Use the connection to delete from metadata table
                        with self._conn:
                            placeholders = ','.join(['?' for _ in ids])
                            self._conn.execute(
                                f"DELETE FROM embeddings_metadata WHERE id IN ({placeholders})",
                                ids
                            )
                            self._conn.commit()
                    
                    # Ensure all other abstract methods are implemented
                    def __init__(self, *args, **kwargs):
                        super().__init__(*args, **kwargs)
                
                # Replace the original class
                sqlite.SqliteMetadataSegment = PatchedSqliteMetadataSegment
                
                print("✅ ChromaDB compatibility patch applied successfully")
                return True
                
        except Exception as e:
            print(f"⚠️ Could not apply ChromaDB patch: {e}")
            return False


class CompatibleChromaClient:
    """A ChromaDB client with compatibility fixes for 0.3.29."""
    
    def __init__(self, persist_directory: Optional[str] = None):
        """Initialize a compatible ChromaDB client."""
        # Apply compatibility patches
        ChromaDBCompatibilityPatch.patch_chromadb()
        
        # Set up ChromaDB path
        self.persist_directory = persist_directory or str(
            Path.home() / ".mira" / "chromadb"
        )
        
        # Ensure directory exists
        Path(self.persist_directory).mkdir(parents=True, exist_ok=True)
        
        # Initialize ChromaDB with 0.3.29 compatible settings
        self._initialize_chromadb()
    
    def _initialize_chromadb(self):
        """Initialize ChromaDB with proper settings for 0.3.29."""
        try:
            # Use settings compatible with 0.3.29
            settings = Settings(
                chroma_db_impl="duckdb+parquet",
                persist_directory=self.persist_directory,
                anonymized_telemetry=False
            )
            
            # Create client with settings
            self.client = chromadb.Client(settings)
            
        except Exception as e:
            print(f"Error initializing ChromaDB: {e}")
            # Fallback to simple client
            self.client = chromadb.Client()
    
    def get_or_create_collection(self, name: str, metadata: Optional[Dict] = None) -> Any:
        """Get or create a collection with compatibility handling."""
        try:
            # Try to get existing collection
            try:
                collection = self.client.get_collection(name)
                return collection
            except:
                # Create new collection if doesn't exist
                pass
            
            # Create collection with metadata
            collection = self.client.create_collection(
                name=name,
                metadata=metadata or {}
            )
            return collection
            
        except Exception as e:
            print(f"Error with collection {name}: {e}")
            raise
    
    def list_collections(self) -> List[Any]:
        """List all collections."""
        return self.client.list_collections()
    
    def delete_collection(self, name: str) -> None:
        """Delete a collection."""
        try:
            self.client.delete_collection(name)
        except Exception as e:
            print(f"Error deleting collection {name}: {e}")
            raise


# Singleton instance
_compatible_client = None

def get_compatible_chromadb_client(persist_directory: Optional[str] = None) -> CompatibleChromaClient:
    """Get or create a compatible ChromaDB client instance."""
    global _compatible_client
    if _compatible_client is None:
        _compatible_client = CompatibleChromaClient(persist_directory)
    return _compatible_client


# Auto-patch on import
ChromaDBCompatibilityPatch.patch_chromadb()