"""
cortex/storage/migrations/v6_operational.py — Operational Layer Tables.

Adds four tables that support the Cortex operational layer:

  - claim_changelog   — immutable audit trail for semantic_claim mutations
  - request_log       — structured log of incoming API / tool requests
  - event_log         — general-purpose event stream (session lifecycle, etc.)
  - webhook           — webhook registrations for event-driven integrations

Migration: version 5 → 6
"""

VERSION = 6
DESCRIPTION = "Add operational layer tables: claim_changelog, request_log, event_log, webhook"

SQL_UP = """
-- -----------------------------------------------------------------------
-- claim_changelog: immutable audit trail for semantic_claim mutations
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS claim_changelog (
    id               TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
    claim_id         TEXT NOT NULL,
    version          INTEGER NOT NULL,
    content_snapshot TEXT NOT NULL,
    action           TEXT NOT NULL,
    reason           TEXT,
    changed_by       TEXT NOT NULL,
    diff_summary     TEXT,
    created_at       TEXT NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (claim_id) REFERENCES semantic_claim(id)
);

CREATE INDEX IF NOT EXISTS idx_changelog_claim
    ON claim_changelog (claim_id, version);

-- -----------------------------------------------------------------------
-- request_log: structured log of incoming API / tool requests
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS request_log (
    id               TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
    owner_id         TEXT NOT NULL DEFAULT 'default',
    request_type     TEXT NOT NULL,
    entities_json    TEXT,
    has_results      INTEGER,
    latency_ms       INTEGER,
    request_payload  TEXT,
    response_summary TEXT,
    status           TEXT DEFAULT 'success',
    session_id       TEXT,
    created_at       TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_reqlog_owner
    ON request_log (owner_id, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_reqlog_type
    ON request_log (request_type, created_at DESC);

-- -----------------------------------------------------------------------
-- event_log: general-purpose event stream
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS event_log (
    id           TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
    owner_id     TEXT NOT NULL DEFAULT 'default',
    event_type   TEXT NOT NULL,
    timestamp    TEXT NOT NULL,
    payload_json TEXT,
    session_id   TEXT,
    created_at   TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_event_owner
    ON event_log (owner_id, timestamp DESC);

CREATE INDEX IF NOT EXISTS idx_event_type
    ON event_log (event_type, timestamp DESC);

-- -----------------------------------------------------------------------
-- webhook: webhook registrations for event-driven integrations
-- TODO(v1.1): The webhook table schema is created here but webhook dispatch
-- is not yet implemented. The WebhookQueryMixin provides CRUD methods for
-- managing webhook registrations, and webhook_delivery logging is stubbed.
-- Full event dispatch (HTTP POST on event_log writes) is planned for v1.1.
-- See: https://github.com/100yenadmin/electric-sheep/issues/224
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS webhook (
    id            TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
    owner_id      TEXT NOT NULL DEFAULT 'default',
    name          TEXT NOT NULL,
    url           TEXT NOT NULL,
    events        TEXT NOT NULL,
    secret        TEXT,
    active        INTEGER DEFAULT 1,
    last_triggered TEXT,
    last_status   INTEGER,
    failure_count INTEGER DEFAULT 0,
    created_at    TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at    TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_webhook_owner
    ON webhook (owner_id, active);
"""

SQL_DOWN = """
DROP INDEX IF EXISTS idx_webhook_owner;
DROP TABLE IF EXISTS webhook;

DROP INDEX IF EXISTS idx_event_type;
DROP INDEX IF EXISTS idx_event_owner;
DROP TABLE IF EXISTS event_log;

DROP INDEX IF EXISTS idx_reqlog_type;
DROP INDEX IF EXISTS idx_reqlog_owner;
DROP TABLE IF EXISTS request_log;

DROP INDEX IF EXISTS idx_changelog_claim;
DROP TABLE IF EXISTS claim_changelog;
"""
