"""Migration 005: Add security audit table for SecureLLM events.

Logs every secret detection, policy decision, and hook action
for audit trail, compliance reporting, and pattern analysis.
"""
from . import register


@register(5, "Add security audit table for SecureLLM events")
def migrate(db) -> None:
    """Create _security_audit table."""
    db.execute("""
        CREATE TABLE IF NOT EXISTS _security_audit (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            event_type TEXT NOT NULL,
            hook_phase TEXT NOT NULL,
            tool_name TEXT NOT NULL DEFAULT '',
            severity TEXT NOT NULL DEFAULT 'info',
            pattern_name TEXT DEFAULT NULL,
            confidence REAL DEFAULT NULL,
            outcome TEXT NOT NULL DEFAULT 'allow',
            rule_id TEXT DEFAULT NULL,
            reason TEXT DEFAULT NULL,
            content_hash TEXT DEFAULT NULL,
            session_id TEXT DEFAULT NULL,
            node_id TEXT DEFAULT NULL,
            created_at TEXT DEFAULT (datetime('now'))
        )
    """)
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_security_audit_type "
        "ON _security_audit(event_type, created_at)"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_security_audit_severity "
        "ON _security_audit(severity, created_at)"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_security_audit_outcome "
        "ON _security_audit(outcome) WHERE outcome != 'allow'"
    )
