"""Migration 007: Create channel_audit_log table.

Append-only audit log for channel operations (sync, share, retract, review).
Supports replay of unattended AI decisions and human-readable audit trails.

Extends the security audit pattern with channel-specific fields:
channel_id, direction, target_node, data_scope, payload, and parent
event linking for multi-step operation chains.
"""
from . import register


@register(7, "Create channel_audit_log table for channel operation auditing")
def migrate(db) -> None:
    """Create the channel_audit_log table and indexes."""
    db.execute("""
        CREATE TABLE IF NOT EXISTS channel_audit_log (
            id TEXT PRIMARY KEY,
            channel_id TEXT NOT NULL,
            operation TEXT NOT NULL,
            severity TEXT NOT NULL DEFAULT 'info',
            outcome TEXT NOT NULL DEFAULT 'success',
            actor TEXT NOT NULL DEFAULT '',
            actor_type TEXT NOT NULL DEFAULT 'system',
            target_node TEXT DEFAULT NULL,
            direction TEXT DEFAULT NULL,
            data_scope TEXT DEFAULT NULL,
            items_affected INTEGER DEFAULT 0,
            detail TEXT DEFAULT NULL,
            payload TEXT DEFAULT NULL,
            session_id TEXT DEFAULT NULL,
            node_id TEXT DEFAULT NULL,
            parent_event_id TEXT DEFAULT NULL,
            created_at TEXT DEFAULT (datetime('now'))
        )
    """)
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_channel_audit_channel "
        "ON channel_audit_log(channel_id, created_at)"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_channel_audit_operation "
        "ON channel_audit_log(operation, created_at)"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_channel_audit_severity "
        "ON channel_audit_log(severity) WHERE severity != 'info'"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_channel_audit_outcome "
        "ON channel_audit_log(outcome) WHERE outcome != 'success'"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_channel_audit_actor "
        "ON channel_audit_log(actor) WHERE actor != ''"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_channel_audit_parent "
        "ON channel_audit_log(parent_event_id) WHERE parent_event_id IS NOT NULL"
    )
