"""
cortex/storage/migrations/v11_contradictions.py — Persistent contradiction audit trail.

Creates the ``contradictions`` table so that the in-memory ContradictionTracker
can durably persist every detected claim–claim conflict, its auto-resolution,
and any subsequent dream-cycle or human-triggered resolution.

Schema
------
  id           — auto-increment PK (INTEGER, so row deletion is unambiguous)
  claim_a_id   — the new/winning claim (FK-by-convention: semantic_claim.id)
  claim_b_id   — the old/superseded claim
  detected_at  — ISO-8601 UTC timestamp of detection
  resolution   — NULL = unresolved | 'kept_a' | 'kept_b' | 'merged'
  resolved_at  — ISO-8601 UTC timestamp when resolved (NULL if still open)
  owner_id     — multi-tenant isolation key (matches semantic_claim.owner_id)
  reason       — free-text description of why the contradiction was flagged

Migration: version 10 → 11
"""

VERSION = 11
DESCRIPTION = (
    "Add contradictions table for persistent contradiction audit trail "
    "(claim_a_id, claim_b_id, detected_at, resolution, resolved_at, owner_id, reason)"
)

SQL_UP = """
CREATE TABLE IF NOT EXISTS contradictions (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    claim_a_id  TEXT    NOT NULL,
    claim_b_id  TEXT    NOT NULL,
    detected_at TEXT    NOT NULL,
    resolution  TEXT    DEFAULT NULL,
    resolved_at TEXT    DEFAULT NULL,
    owner_id    TEXT    NOT NULL DEFAULT 'default',
    reason      TEXT    NOT NULL DEFAULT ''
);

-- Fast lookup: all unresolved contradictions for a given owner
CREATE INDEX IF NOT EXISTS idx_contradictions_owner_unresolved
    ON contradictions(owner_id, detected_at)
    WHERE resolution IS NULL;

-- Lookup by either claim ID (e.g. "what contradictions touch claim X?")
CREATE INDEX IF NOT EXISTS idx_contradictions_claim_a
    ON contradictions(claim_a_id);

CREATE INDEX IF NOT EXISTS idx_contradictions_claim_b
    ON contradictions(claim_b_id);

-- Full owner timeline (resolved + unresolved) ordered by detection time
CREATE INDEX IF NOT EXISTS idx_contradictions_owner_all
    ON contradictions(owner_id, detected_at);
"""

# Downgrade: drop indexes then table.  Data loss is intentional on downgrade.
SQL_DOWN = """
DROP INDEX IF EXISTS idx_contradictions_owner_all;
DROP INDEX IF EXISTS idx_contradictions_claim_b;
DROP INDEX IF EXISTS idx_contradictions_claim_a;
DROP INDEX IF EXISTS idx_contradictions_owner_unresolved;
DROP TABLE IF EXISTS contradictions;
"""
