"""
cortex/storage/migrations/v27_hotness_score.py — Add hotness_score column.

Issue #1343: Hotness scoring engine for memory lifecycle management.
Adds the hotness_score column to semantic_claim and an index for efficient
archival queries (owner_id, hotness_score).

Migration: version 26 → 27
(v26 is reserved for orphan_sessions — PR #1468.)
"""

VERSION = 27
DESCRIPTION = "Add hotness_score column to semantic_claim (#1343)"

# B-014: SQL_UP is NOT safe to executescript() directly because ALTER TABLE
# ADD COLUMN is not idempotent in SQLite. Always use apply() which checks
# PRAGMA table_info before altering. SQL_UP kept as documentation only.
SQL_UP = """
-- NOTE: Do not executescript(SQL_UP) directly; use apply() for idempotency.
-- ALTER TABLE semantic_claim ADD COLUMN hotness_score REAL DEFAULT 0.0;
CREATE INDEX IF NOT EXISTS idx_claim_hotness ON semantic_claim(owner_id, hotness_score);
"""

SQL_DOWN = """
DROP INDEX IF EXISTS idx_claim_hotness;
-- SQLite does not support DROP COLUMN before 3.35.0; column remains but is unused.
"""


async def apply(conn) -> None:
    """Add hotness_score column (idempotent)."""
    # Check if column already exists (idempotent for re-runs)
    cursor = await conn.execute("PRAGMA table_info(semantic_claim)")
    columns = [row[1] for row in await cursor.fetchall()]
    if "hotness_score" not in columns:
        await conn.execute(
            "ALTER TABLE semantic_claim ADD COLUMN hotness_score REAL DEFAULT 0.0"
        )
    await conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_claim_hotness ON semantic_claim(owner_id, hotness_score)"
    )
    await conn.commit()
