"""
cortex/storage/migrations/v22_peer_promotion.py — Promote peer table to canonical actor identity (#932).

Adds peer_type, status, permissions_json, description, promoted_at,
promotion_reason, and connection_count columns to the peer table.
Migration is idempotent (try/except per ALTER TABLE).

Migration: version 21 → 22
"""

VERSION = 22
DESCRIPTION = "Promote peer table to canonical actor identity (#932)"


SQL_UP = ""  # Applied via apply() for idempotent ALTER TABLE support

async def apply(conn) -> None:
    """Add promotion columns to peer table (idempotent)."""
    alter_statements = [
        "ALTER TABLE peer ADD COLUMN peer_type TEXT DEFAULT 'person'",
        "ALTER TABLE peer ADD COLUMN status TEXT DEFAULT 'active'",
        "ALTER TABLE peer ADD COLUMN permissions_json TEXT DEFAULT '{}'",
        "ALTER TABLE peer ADD COLUMN description TEXT",
        "ALTER TABLE peer ADD COLUMN promoted_at TEXT",
        "ALTER TABLE peer ADD COLUMN promotion_reason TEXT",
        "ALTER TABLE peer ADD COLUMN connection_count INTEGER DEFAULT 0",
    ]
    for stmt in alter_statements:
        try:
            await conn.execute(stmt)
        except Exception:
            pass  # Column already exists — idempotent

    # Indexes
    index_statements = [
        "CREATE INDEX IF NOT EXISTS idx_peer_type ON peer(peer_type)",
        "CREATE INDEX IF NOT EXISTS idx_peer_status ON peer(status)",
    ]
    for stmt in index_statements:
        await conn.execute(stmt)

    await conn.commit()
