-- Durable EwoooC / MOMO MCP-RAG federation receipts.
--
-- Safety contract:
--   * exact production source and exact two canonical product identities;
--   * normalized aggregate runtime metadata only (no endpoint, credential,
--     request/response body, raw payload, tool output, or RAG content);
--   * additive evidence schema with project-scoped FORCE RLS;
--   * every receipt shares one run_id / trace_id / work_item_id and is checked
--     again from durable columns before the run can become verified.

BEGIN;

CREATE TABLE IF NOT EXISTS awooop_mcp_federation_run (
    run_id                         UUID PRIMARY KEY,
    trace_id                       VARCHAR(128) NOT NULL,
    work_item_id                   VARCHAR(128) NOT NULL,
    project_id                     VARCHAR(64) NOT NULL,
    source_id                      VARCHAR(64) NOT NULL,
    trigger_kind                   VARCHAR(32) NOT NULL,
    status                         VARCHAR(64) NOT NULL,
    expected_product_count         INTEGER NOT NULL DEFAULT 2,
    received_product_count         INTEGER NOT NULL DEFAULT 0,
    verified_product_count         INTEGER NOT NULL DEFAULT 0,
    runtime_blocked_product_count  INTEGER NOT NULL DEFAULT 0,
    error_count                    INTEGER NOT NULL DEFAULT 0,
    error_class                    VARCHAR(128),
    receipt                        JSONB NOT NULL DEFAULT '{}'::jsonb,
    started_at                     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    ended_at                       TIMESTAMPTZ,

    CONSTRAINT uix_mcp_federation_trace UNIQUE (project_id, trace_id),
    CONSTRAINT chk_mcp_federation_run_project CHECK (project_id = 'awoooi'),
    CONSTRAINT chk_mcp_federation_run_source
        CHECK (source_id = 'ewoooc-momo-production'),
    CONSTRAINT chk_mcp_federation_run_trigger
        CHECK (trigger_kind IN ('startup','scheduled','operator_replay','test')),
    CONSTRAINT chk_mcp_federation_run_status
        CHECK (status IN (
            'running',
            'completed_verified',
            'completed_verified_with_runtime_blockers',
            'partial_degraded',
            'failed'
        )),
    CONSTRAINT chk_mcp_federation_run_counts CHECK (
        expected_product_count = 2
        AND received_product_count BETWEEN 0 AND 2
        AND verified_product_count BETWEEN 0 AND received_product_count
        AND runtime_blocked_product_count BETWEEN 0 AND received_product_count
        AND error_count BETWEEN 0 AND 2
    ),
    CONSTRAINT chk_mcp_federation_run_terminal_time CHECK (
        (status = 'running' AND ended_at IS NULL)
        OR (status <> 'running' AND ended_at IS NOT NULL)
    )
);

CREATE TABLE IF NOT EXISTS awooop_mcp_federated_runtime_receipt (
    receipt_row_id                  UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    run_id                          UUID NOT NULL
        REFERENCES awooop_mcp_federation_run(run_id) ON DELETE RESTRICT,
    trace_id                        VARCHAR(128) NOT NULL,
    work_item_id                    VARCHAR(128) NOT NULL,
    project_id                      VARCHAR(64) NOT NULL,
    source_id                       VARCHAR(64) NOT NULL,
    product_id                      VARCHAR(64) NOT NULL,
    canonical_repo                  VARCHAR(128) NOT NULL,
    runtime_role                    VARCHAR(96) NOT NULL,
    runtime_version                 VARCHAR(64) NOT NULL,
    health_status                   VARCHAR(32) NOT NULL,
    change_state                    VARCHAR(32) NOT NULL,
    normalized_fingerprint_sha256   VARCHAR(64) NOT NULL,
    mcp_enabled                     BOOLEAN NOT NULL,
    mcp_server_count                INTEGER NOT NULL,
    mcp_server_ids                  JSONB NOT NULL DEFAULT '[]'::jsonb,
    mcp_caller_count                INTEGER NOT NULL,
    mcp_tool_count                  INTEGER NOT NULL,
    rag_enabled                     BOOLEAN NOT NULL,
    rag_vector_store                VARCHAR(32) NOT NULL,
    rag_embedding_model             VARCHAR(160) NOT NULL,
    rag_embedding_dim               INTEGER NOT NULL,
    rag_embedding_signature         VARCHAR(256) NOT NULL,
    rag_embedding_version_state     VARCHAR(32) NOT NULL,
    pixelrag_enabled                BOOLEAN NOT NULL,
    pixelrag_platform_count         INTEGER NOT NULL,
    pixelrag_platforms              JSONB NOT NULL DEFAULT '[]'::jsonb,
    pixelrag_visual_rag_stage       VARCHAR(64) NOT NULL,
    runtime_blockers                JSONB NOT NULL DEFAULT '[]'::jsonb,
    verifier_status                 VARCHAR(32) NOT NULL,
    stage_receipts                  JSONB NOT NULL DEFAULT '{}'::jsonb,
    observed_at                     TIMESTAMPTZ NOT NULL,
    received_at                     TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    CONSTRAINT uix_mcp_federated_receipt_run_product
        UNIQUE (run_id, product_id),
    CONSTRAINT chk_mcp_federated_receipt_project
        CHECK (project_id = 'awoooi'),
    CONSTRAINT chk_mcp_federated_receipt_source
        CHECK (source_id = 'ewoooc-momo-production'),
    CONSTRAINT chk_mcp_federated_receipt_product
        CHECK (product_id IN ('ewoooc','momo-pro-system')),
    CONSTRAINT chk_mcp_federated_receipt_identity CHECK (
        (product_id = 'ewoooc'
         AND canonical_repo = 'wooo/ewoooc'
         AND runtime_role = 'mcp_rag_automation_source_plane')
        OR
        (product_id = 'momo-pro-system'
         AND canonical_repo = 'wooo/momo-pro-system'
         AND runtime_role = 'commerce_runtime_consumer_plane')
    ),
    CONSTRAINT chk_mcp_federated_receipt_health
        CHECK (health_status IN ('ready','partial_degraded')),
    CONSTRAINT chk_mcp_federated_receipt_change
        CHECK (change_state IN ('baseline_created','no_change','runtime_changed')),
    CONSTRAINT chk_mcp_federated_receipt_fingerprint
        CHECK (normalized_fingerprint_sha256 ~ '^[0-9a-f]{64}$'),
    CONSTRAINT chk_mcp_federated_receipt_mcp_counts CHECK (
        mcp_server_count BETWEEN 0 AND 32
        AND mcp_caller_count BETWEEN 0 AND 64
        AND mcp_tool_count BETWEEN 0 AND 1000
        AND jsonb_typeof(mcp_server_ids) = 'array'
        AND jsonb_array_length(mcp_server_ids) = mcp_server_count
    ),
    CONSTRAINT chk_mcp_federated_receipt_rag CHECK (
        rag_vector_store = 'pgvector'
        AND rag_embedding_dim BETWEEN 0 AND 65536
        AND rag_embedding_version_state IN (
            'floating_tag_detected','explicit_or_unknown'
        )
    ),
    CONSTRAINT chk_mcp_federated_receipt_pixelrag CHECK (
        pixelrag_platform_count BETWEEN 0 AND 32
        AND jsonb_typeof(pixelrag_platforms) = 'array'
        AND jsonb_array_length(pixelrag_platforms) = pixelrag_platform_count
    ),
    CONSTRAINT chk_mcp_federated_receipt_blockers
        CHECK (jsonb_typeof(runtime_blockers) = 'array'),
    CONSTRAINT chk_mcp_federated_receipt_verifier
        CHECK (verifier_status = 'verified')
);

CREATE INDEX IF NOT EXISTS idx_mcp_federation_run_recent
    ON awooop_mcp_federation_run (project_id, source_id, started_at DESC);

CREATE INDEX IF NOT EXISTS idx_mcp_federated_receipt_product_recent
    ON awooop_mcp_federated_runtime_receipt
        (project_id, product_id, received_at DESC);

CREATE INDEX IF NOT EXISTS idx_mcp_federated_receipt_run
    ON awooop_mcp_federated_runtime_receipt
        (project_id, run_id, received_at);

ALTER TABLE awooop_mcp_federation_run ENABLE ROW LEVEL SECURITY;
ALTER TABLE awooop_mcp_federation_run FORCE ROW LEVEL SECURITY;
ALTER TABLE awooop_mcp_federated_runtime_receipt ENABLE ROW LEVEL SECURITY;
ALTER TABLE awooop_mcp_federated_runtime_receipt FORCE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS mcp_federation_run_tenant ON awooop_mcp_federation_run;
CREATE POLICY mcp_federation_run_tenant ON awooop_mcp_federation_run
    USING (project_id = current_setting('app.project_id', TRUE))
    WITH CHECK (project_id = current_setting('app.project_id', TRUE));

DROP POLICY IF EXISTS mcp_federated_receipt_tenant
    ON awooop_mcp_federated_runtime_receipt;
CREATE POLICY mcp_federated_receipt_tenant
    ON awooop_mcp_federated_runtime_receipt
    USING (project_id = current_setting('app.project_id', TRUE))
    WITH CHECK (project_id = current_setting('app.project_id', TRUE));

GRANT SELECT, INSERT, UPDATE ON awooop_mcp_federation_run TO awooop_app;
GRANT SELECT, INSERT ON awooop_mcp_federated_runtime_receipt TO awooop_app;
GRANT SELECT, INSERT, UPDATE ON awooop_mcp_federation_run TO awoooi;
GRANT SELECT, INSERT ON awooop_mcp_federated_runtime_receipt TO awoooi;

COMMENT ON TABLE awooop_mcp_federation_run IS
    'Controlled read-only EwoooC/MOMO federation run receipts; no raw payload.';
COMMENT ON TABLE awooop_mcp_federated_runtime_receipt IS
    'Normalized product MCP/RAG runtime metadata with durable hash verifier.';

COMMIT;
