"""
Migration: add performance indexes for time-range queries.

Adds created_at and (conversation_id, created_at) indexes on
hippo_messages and hippo_summaries for faster time-range scans.

Issue: #1185
"""

from __future__ import annotations

import logging

import aiosqlite

logger = logging.getLogger(__name__)

MIGRATION_NAME = "add_performance_indexes"
MIGRATION_VERSION = 3  # bumps from schema v2

_INDEXES = [
    "CREATE INDEX IF NOT EXISTS idx_hippo_messages_created ON hippo_messages(created_at)",
    "CREATE INDEX IF NOT EXISTS idx_hippo_messages_conv_created ON hippo_messages(conversation_id, created_at)",
    "CREATE INDEX IF NOT EXISTS idx_hippo_summaries_created ON hippo_summaries(created_at)",
    "CREATE INDEX IF NOT EXISTS idx_hippo_summaries_conv_created ON hippo_summaries(conversation_id, created_at)",
]


async def needs_migration(conn: aiosqlite.Connection) -> bool:
    """Check if the performance indexes already exist."""
    async with conn.execute(
        "SELECT name FROM sqlite_master WHERE type='index' AND name='idx_hippo_messages_created'"
    ) as cur:
        row = await cur.fetchone()
    return row is None


async def migrate(conn: aiosqlite.Connection) -> None:
    """Add performance indexes to hippo_messages and hippo_summaries."""
    if not await needs_migration(conn):
        logger.info("Migration %s: already applied, skipping", MIGRATION_NAME)
        return

    logger.info("Migration %s: adding performance indexes", MIGRATION_NAME)

    for idx_sql in _INDEXES:
        await conn.execute(idx_sql)

    # Update schema version
    await conn.execute(
        """
        INSERT INTO hippo_config (key, value, updated_at)
        VALUES ('schema_version', ?, strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
        ON CONFLICT(key) DO UPDATE SET
            value = excluded.value,
            updated_at = excluded.updated_at
        """,
        (str(MIGRATION_VERSION),),
    )
    await conn.commit()

    logger.info("Migration %s: complete", MIGRATION_NAME)
