"""
VibeDB Indexing System Test

Demonstrates indexing, slow query analysis, and automatic index suggestions.
"""

from vibedb import VibeDB, Q
import time


def main():
    print("🗂️  VibeDB Indexing System Test\n")

    # Create database with slow query threshold
    db = VibeDB(":memory:", slow_query_threshold_ms=50)
    users = db.collection("users")

    # Insert test data (more data to make queries slower)
    print("📝 Inserting test data...")
    for i in range(1000):  # Increased from 100 to 1000
        users.insert({
            "name": f"User{i}",
            "age": 20 + (i % 50),
            "email": f"user{i}@example.com",
            "status": "active" if i % 3 == 0 else "inactive",
            "score": i * 10,
            "tags": ["python", "ml"] if i % 2 == 0 else ["javascript", "web"]
        })
    print(f"  ✓ Inserted {users.count()} users\n")

    # Test 1: Manual index creation
    print("📊 Test 1: Create Indexes Manually")
    print("  Creating index on 'email' (unique)...")
    idx1 = users.create_index(["email"], unique=True)
    print(f"  ✓ Created: {idx1}")

    print("  Creating composite index on ['age', 'status']...")
    idx2 = users.create_index(["age", "status"])
    print(f"  ✓ Created: {idx2}")

    print("\n  Listing indexes:")
    indexes = users.list_indexes()
    for idx in indexes:
        unique_str = " (unique)" if idx['unique'] else ""
        print(f"    • {idx['name']}: {idx['fields']}{unique_str}")

    # Test 2: Manually log slow queries for testing
    print("\n⏱️  Test 2: Simulate Slow Queries")
    print("  Manually logging slow queries for testing...")

    # Drop indexes temporarily
    for idx in indexes:
        users.drop_index(idx['name'])

    # Manually log some slow queries (simulating what would happen in production)
    from vibedb.indexes.analyzer import SlowQueryAnalyzer
    analyzer = SlowQueryAnalyzer(users, threshold_ms=50)

    # Simulate different slow queries
    analyzer.log_query({"score": {"$gte": 500}}, 150.5)
    analyzer.log_query({"score": {"$gte": 600}}, 145.2)
    analyzer.log_query({"score": {"$gte": 700}}, 152.8)
    analyzer.log_query({"status": {"$eq": "active"}}, 120.1)
    analyzer.log_query({"status": {"$eq": "active"}}, 118.5)
    analyzer.log_query({"status": {"$eq": "active"}}, 125.3)
    analyzer.log_query({"status": {"$eq": "active"}}, 122.7)
    analyzer.log_query({"email": {"$contains": "@example.com"}}, 180.2)
    analyzer.log_query({"email": {"$contains": "@example.com"}}, 175.8)

    print("  ✓ Logged 9 slow queries")

    # Test 3: Get slow query stats
    print("\n📈 Test 3: Slow Query Statistics")
    from vibedb.indexes.analyzer import SlowQueryAnalyzer

    analyzer = SlowQueryAnalyzer(users, threshold_ms=50)
    stats = analyzer.get_query_stats()

    print(f"  Total slow queries: {stats['total_count']}")
    if stats['total_count'] > 0:
        print(f"  Average time: {stats['avg_execution_time_ms']:.1f}ms")
        print(f"  Max time: {stats['max_execution_time_ms']:.1f}ms")
    else:
        print("  (No slow queries recorded - queries were too fast!)")

    if stats['most_queried_fields']:
        print("\n  Most queried fields:")
        for field_stat in stats['most_queried_fields'][:5]:
            print(f"    • {field_stat['field']}: {field_stat['query_count']} queries, "
                  f"avg {field_stat['avg_execution_time_ms']:.1f}ms")

    # Test 4: Get index suggestions
    print("\n💡 Test 4: Index Suggestions")
    suggestions = users.index_suggestions()

    if suggestions:
        print(f"  Found {len(suggestions)} suggestions:")
        for i, s in enumerate(suggestions[:5], 1):
            print(f"\n  {i}. Index on {s['fields']}")
            print(f"     Reason: {s['reason']}")
            print(f"     Estimated speedup: {s['estimated_speedup']}")
            print(f"     Priority: {s['priority']:.1f}")
    else:
        print("  No suggestions (not enough slow query data)")

    # Test 5: Apply suggestions
    print("\n✨ Test 5: Apply Index Suggestions")
    if suggestions:
        # Apply top suggestion
        top_suggestion = suggestions[0]
        print(f"  Applying suggestion: {top_suggestion['fields']}")
        users.create_index(top_suggestion['fields'])
        print("  ✓ Index created")

        # Check indexes again
        print("\n  Updated index list:")
        indexes = users.list_indexes()
        for idx in indexes:
            print(f"    • {idx['name']}: {idx['fields']}")

    # Test 6: Auto-create indexes (dry run)
    print("\n🤖 Test 6: Auto-Create Indexes (Preview)")
    from vibedb.indexes.suggestions import IndexSuggestionEngine

    engine = IndexSuggestionEngine(users)
    preview = engine.auto_create_indexes(min_priority=5.0, max_indexes=3, dry_run=True)

    if preview:
        print(f"  Would create {len(preview)} indexes:")
        for p in preview:
            print(f"    • {p['fields']}: {p['reason']}")
    else:
        print("  No high-priority indexes to create")

    # Test 7: Drop index
    print("\n🗑️  Test 7: Drop Index")
    if indexes:
        first_index = indexes[0]
        print(f"  Dropping: {first_index['name']}")
        success = users.drop_index(first_index['name'])
        print(f"  ✓ Dropped: {success}")

        remaining = users.list_indexes()
        print(f"  Remaining indexes: {len(remaining)}")

    # Test 8: Clear slow query log
    print("\n🧹 Test 8: Clear Slow Query Log")
    cleared = analyzer.clear_slow_queries()
    print(f"  ✓ Cleared {cleared} slow queries")

    stats_after = analyzer.get_query_stats()
    print(f"  Slow queries now: {stats_after['total_count']}")

    db.close()
    print("\n✅ All indexing tests completed!")


if __name__ == "__main__":
    main()
