"""
Migration: add session_key column to hippo_conversations.

Adds a nullable TEXT column for stable session key lookup, plus a
composite index on (owner_id, session_key) for fast queries.

Issue: #1179
"""

from __future__ import annotations

import logging

import aiosqlite

logger = logging.getLogger(__name__)

MIGRATION_NAME = "add_session_key"
MIGRATION_VERSION = 2  # bumps from schema v1


async def needs_migration(conn: aiosqlite.Connection) -> bool:
    """Check if the session_key column already exists."""
    async with conn.execute("PRAGMA table_info(hippo_conversations)") as cur:
        columns = [row[1] async for row in cur]
    return "session_key" not in columns


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

    logger.info("Migration %s: adding session_key column", MIGRATION_NAME)

    await conn.execute(
        "ALTER TABLE hippo_conversations ADD COLUMN session_key TEXT"
    )
    await conn.execute(
        """
        CREATE INDEX IF NOT EXISTS idx_hippo_conversations_owner_session_key
            ON hippo_conversations(owner_id, session_key)
        """
    )

    # 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)
