"""
cortex/storage/migrations/v28_cornerstone_category.py — Add category column to cornerstone_memory.

Issue #712 / #713 (Phase 1): Restructure cornerstone injection into ordered category blocks.
Adds a ``category`` TEXT column (NOT NULL DEFAULT 'memory') to ``cornerstone_memory`` so that
cornerstones can be grouped into named injection blocks without altering existing rows.

Valid categories: memory | anchor | meta_story | guardrail | other

Migration: version 27 → 28
"""

VERSION = 28
DESCRIPTION = "Add category column to cornerstone_memory for ordered block injection (#712/#713)"

SQL_UP = "SELECT 1;"  # All logic routed through apply() for idempotency

SQL_DOWN = """
DROP INDEX IF EXISTS idx_cs_category;
-- SQLite does not support DROP COLUMN in older versions; no-op downgrade.
SELECT 1;
"""


async def apply(conn) -> None:
    """Add category column — idempotent (skips if column already exists)."""
    cur = await conn.execute("PRAGMA table_info(cornerstone_memory)")
    rows = await cur.fetchall()
    existing_columns = {row[1] for row in rows}
    if "category" not in existing_columns:
        await conn.execute(
            "ALTER TABLE cornerstone_memory ADD COLUMN category TEXT NOT NULL DEFAULT 'memory'"
        )
    await conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_cs_category ON cornerstone_memory(owner_id, category)"
    )
    await conn.commit()


async def upgrade(conn) -> None:
    """Alias for apply()."""
    await apply(conn)


async def downgrade(conn) -> None:
    """SQLite does not support DROP COLUMN — no-op."""
    pass
