"""
MongoDB Index Creation Script

Creates all necessary indexes for optimized queries.
Run this script after migration to ensure indexes are in place.

Usage:
  python backend/scripts/create_indexes.py
"""

from pymongo import MongoClient
from config import get_settings
from typing import Dict, List, Tuple


def create_indexes():
    """Create all required MongoDB indexes."""

    settings = get_settings()
    client = MongoClient(settings.mongodb_uri)
    db = client[settings.mongodb_db_name]

    print(f"✓ Connected to MongoDB: {settings.mongodb_db_name}\n")

    indexes_created = []

    # ========== USERS COLLECTION INDEXES ==========
    print("Creating indexes for 'users' collection...")

    # Unique index on email
    try:
        db.users.create_index(
            [("email", 1)],
            unique=True,
            name="email_unique"
        )
        indexes_created.append(("users", "email_unique"))
        print("  ✓ Created unique index on email")
    except Exception as e:
        print(f"  ⚠ Email index: {e}")

    # Index on createdAt for sorting
    try:
        db.users.create_index(
            [("createdAt", -1)],
            name="createdAt_desc"
        )
        indexes_created.append(("users", "createdAt_desc"))
        print("  ✓ Created index on createdAt")
    except Exception as e:
        print(f"  ⚠ createdAt index: {e}")

    # ========== ENTRIES COLLECTION INDEXES ==========
    print("\nCreating indexes for 'entries' collection...")

    # Compound index: userId + createdAt (for history pagination)
    try:
        db.entries.create_index(
            [("userId", 1), ("createdAt", -1)],
            name="userId_createdAt"
        )
        indexes_created.append(("entries", "userId_createdAt"))
        print("  ✓ Created compound index on (userId, createdAt)")
    except Exception as e:
        print(f"  ⚠ userId_createdAt index: {e}")

    # Compound index: userId + entryDate (for calendar queries)
    try:
        db.entries.create_index(
            [("userId", 1), ("entryDate", 1)],
            name="userId_entryDate"
        )
        indexes_created.append(("entries", "userId_entryDate"))
        print("  ✓ Created compound index on (userId, entryDate)")
    except Exception as e:
        print(f"  ⚠ userId_entryDate index: {e}")

    # Index on tags for searching (optional, for future)
    try:
        db.entries.create_index(
            [("tags", 1)],
            name="tags"
        )
        indexes_created.append(("entries", "tags"))
        print("  ✓ Created index on tags")
    except Exception as e:
        print(f"  ⚠ tags index: {e}")

    # Index on entryDate range queries (for calendar)
    try:
        db.entries.create_index(
            [("entryDate", -1)],
            name="entryDate_desc"
        )
        indexes_created.append(("entries", "entryDate_desc"))
        print("  ✓ Created index on entryDate")
    except Exception as e:
        print(f"  ⚠ entryDate index: {e}")

    # TTL Index on entries (optional: for auto-deleting old entries if needed)
    # Uncomment if you want entries to auto-delete after 2 years
    # try:
    #     db.entries.create_index(
    #         [("createdAt", 1)],
    #         expireAfterSeconds=63072000,  # 2 years
    #         name="createdAt_ttl"
    #     )
    #     print("  ✓ Created TTL index on createdAt (2 years)")
    # except Exception as e:
    #     print(f"  ⚠ TTL index: {e}")

    # ========== SUMMARY ==========
    print(f"\n{'='*60}")
    print(f"✓ Index Creation Complete")
    print(f"{'='*60}")
    print(f"Total indexes created: {len(indexes_created)}")
    for collection, index_name in indexes_created:
        print(f"  • {collection}.{index_name}")

    # Optional: Print summary of all indexes
    print(f"\n{'='*60}")
    print("All Indexes Summary")
    print(f"{'='*60}")

    for collection_name in ["users", "entries"]:
        print(f"\n{collection_name}:")
        collection = db[collection_name]
        for index_info in collection.list_indexes():
            print(f"  • {index_info['name']}")

    client.close()
    print("\n✓ Disconnected from MongoDB")


if __name__ == "__main__":
    create_indexes()
