#!/usr/bin/env python3
"""
ChromaDB SQLite Compatibility Checker and Fixer
This script checks if your system needs the pysqlite3-binary fix for ChromaDB
"""

import subprocess
import sys
import os

def main():
    print("\n🔧 ChromaDB SQLite Compatibility Fix")
    print("─" * 50)
    
    # Check system SQLite version
    print("\n📊 Checking system SQLite version...")
    import sqlite3
    print(f"  System SQLite: {sqlite3.sqlite_version}")
    print("  ChromaDB requires: 3.35.0+")
    
    if tuple(map(int, sqlite3.sqlite_version.split('.'))) >= (3, 35, 0):
        print("\n✅ Your system SQLite is already compatible with ChromaDB!")
        return 0
    
    print("\n⚠️  System SQLite is too old for ChromaDB")
    
    # Install pysqlite3-binary
    print("\n📦 Installing pysqlite3-binary...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "pysqlite3-binary"])
        print("✓ pysqlite3-binary installed successfully")
    except subprocess.CalledProcessError:
        print("✗ Failed to install pysqlite3-binary")
        print("\nPlease install manually:")
        print("  pip install pysqlite3-binary")
        return 1
    
    # Create the SQLite fix file
    print("\n📝 Creating ChromaDB SQLite fix module...")
    
    # Find the python-memory directory
    script_dir = os.path.dirname(os.path.abspath(__file__))
    python_memory_dir = os.path.join(os.path.dirname(script_dir), 'python-memory')
    fix_path = os.path.join(python_memory_dir, 'chromadb_sqlite_fix.py')
    
    fix_content = '''"""
ChromaDB SQLite Fix - Use pysqlite3 instead of built-in sqlite3

This module replaces the system sqlite3 with pysqlite3-binary to meet
ChromaDB's SQLite 3.35.0+ requirement.

Auto-generated by MIRA setup to ensure ChromaDB compatibility.
"""

import sys

def apply_sqlite_fix():
    """Replace sqlite3 with pysqlite3 to meet ChromaDB requirements."""
    try:
        # Import pysqlite3
        import pysqlite3
        
        # Replace sqlite3 with pysqlite3 in sys.modules
        sys.modules['sqlite3'] = pysqlite3
        sys.modules['sqlite3.dbapi2'] = pysqlite3.dbapi2
        
        # Verify the version
        import sqlite3
        version = sqlite3.sqlite_version
        print(f"✅ SQLite upgraded to version {version} using pysqlite3-binary")
        
        return True
        
    except ImportError:
        print("❌ pysqlite3-binary not installed. Run: pip install pysqlite3-binary")
        return False


# Apply the fix immediately when imported
if __name__ != "__main__":
    apply_sqlite_fix()
'''
    
    os.makedirs(os.path.dirname(fix_path), exist_ok=True)
    with open(fix_path, 'w') as f:
        f.write(fix_content)
    
    print(f"✓ Fix module created at: {fix_path}")
    
    # Test the fix
    print("\n🧪 Testing the fix...")
    try:
        sys.path.insert(0, python_memory_dir)
        import chromadb_sqlite_fix
        import chromadb
        print(f"ChromaDB version: {chromadb.__version__}")
        print("✅ ChromaDB is now compatible!")
        
        print("\n✨ ChromaDB SQLite fix applied successfully!")
        print("\nThe fix will be automatically applied when using MIRA.")
        print("Your workspace is now ready for ChromaDB operations.")
        
    except ImportError as e:
        print("\n⚠️  Fix created but ChromaDB test failed")
        print("This is normal if ChromaDB is not yet installed.")
        print("The fix will work once ChromaDB is installed.")
    
    return 0

if __name__ == "__main__":
    sys.exit(main())