"""
cortex/storage/migrations/v25_embedding_backfill.py — Embedding backfill worker table (#1443).

Creates the embedding_backfill table used by the background worker to track
claims that need their embeddings generated. The worker scans for claims
missing from embedding_index and queues them here for processing.

Migration: version 24 → 25
"""

VERSION = 25
DESCRIPTION = "Add embedding_backfill table for background embedding worker (#1443)"

SQL_UP = """
CREATE TABLE IF NOT EXISTS embedding_backfill (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    claim_id     TEXT NOT NULL UNIQUE,
    status       TEXT NOT NULL DEFAULT 'pending',
    attempts     INTEGER NOT NULL DEFAULT 0,
    last_error   TEXT,
    created_at   TEXT NOT NULL,
    started_at   TEXT,
    completed_at TEXT
);

CREATE INDEX IF NOT EXISTS idx_backfill_status ON embedding_backfill(status);
"""

SQL_DOWN = """
DROP INDEX IF EXISTS idx_backfill_status;
DROP TABLE IF EXISTS embedding_backfill;
"""


async def apply(conn) -> None:
    """Create the embedding_backfill table (idempotent)."""
    for statement in SQL_UP.strip().split(";"):
        stmt = statement.strip()
        if stmt:
            await conn.execute(stmt)
    await conn.commit()
