#!/usr/bin/env python3
"""
Script to apply performance indexes to the inventory database
Usage: python apply_indexes.py
"""

import asyncio
import os
import sys
from pathlib import Path

# Add parent directory to path to import app modules
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy import text
from app.core.database import database_manager
import structlog

logger = structlog.get_logger()


async def apply_indexes():
    """Apply performance indexes from SQL file"""
    try:
        # Read the SQL file
        sql_file = Path(__file__).parent / "001_add_performance_indexes.sql"
        with open(sql_file, 'r') as f:
            sql_content = f.read()

        logger.info("Applying performance indexes...")

        # Split by semicolons and execute each statement
        statements = [s.strip() for s in sql_content.split(';') if s.strip() and not s.strip().startswith('--')]

        async with database_manager.get_session() as session:
            for statement in statements:
                if statement:
                    logger.info(f"Executing: {statement[:100]}...")
                    await session.execute(text(statement))

            await session.commit()
            logger.info(f"Successfully applied {len(statements)} index statements")

        return True

    except Exception as e:
        logger.error(f"Failed to apply indexes: {e}", exc_info=True)
        return False


async def verify_indexes():
    """Verify that indexes were created"""
    try:
        logger.info("Verifying indexes...")

        verify_query = """
        SELECT
            schemaname,
            tablename,
            indexname,
            indexdef
        FROM pg_indexes
        WHERE indexname LIKE 'idx_%'
        AND schemaname = 'public'
        ORDER BY tablename, indexname;
        """

        async with database_manager.get_session() as session:
            result = await session.execute(text(verify_query))
            indexes = result.fetchall()

            logger.info(f"Found {len(indexes)} indexes:")
            for idx in indexes:
                logger.info(f"  {idx.tablename}.{idx.indexname}")

        return True

    except Exception as e:
        logger.error(f"Failed to verify indexes: {e}", exc_info=True)
        return False


async def main():
    """Main entry point"""
    logger.info("Starting index migration...")

    # Apply indexes
    success = await apply_indexes()

    if success:
        # Verify indexes
        await verify_indexes()
        logger.info("Index migration completed successfully")
    else:
        logger.error("Index migration failed")
        sys.exit(1)

    # Close database connections
    await database_manager.close_connections()


if __name__ == "__main__":
    asyncio.run(main())
