"""v16 — Deep Dream tables: dreams, curiosity_seeds, dream_state.

Implements Gen1 Soul restoration (#772):
  - dreams: stores deep dream outputs with quality scores
  - curiosity_seeds: curated + extracted seed questions for exploration
  - dream_state: tracks active/retired dream threads across cycles
"""

VERSION = 18
DESCRIPTION = "Add deep dream tables: dreams, curiosity_seeds, dream_state (#772)"

SQL_UP = """
-- Deep dream outputs with quality self-assessment
CREATE TABLE IF NOT EXISTS dreams (
    id TEXT PRIMARY KEY,
    owner_id TEXT NOT NULL DEFAULT 'default',
    seed_id TEXT,
    seed_content TEXT,
    thread_id TEXT,
    content TEXT NOT NULL,
    what_i_found TEXT,
    what_i_think TEXT,
    what_i_feel TEXT,
    thread_output TEXT,
    depth_score INTEGER DEFAULT 0,
    discovery_score INTEGER DEFAULT 0,
    emotional_resonance_score INTEGER DEFAULT 0,
    model_used TEXT,
    duration_ms INTEGER DEFAULT 0,
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
    claim_id TEXT
);

CREATE INDEX IF NOT EXISTS idx_dreams_owner ON dreams(owner_id);
CREATE INDEX IF NOT EXISTS idx_dreams_thread ON dreams(thread_id);
CREATE INDEX IF NOT EXISTS idx_dreams_created ON dreams(created_at);

-- Curated curiosity seeds for deep dream exploration
CREATE TABLE IF NOT EXISTS curiosity_seeds (
    id TEXT PRIMARY KEY,
    content TEXT NOT NULL,
    category TEXT NOT NULL DEFAULT 'philosophical',
    source TEXT NOT NULL DEFAULT 'manual',
    active INTEGER NOT NULL DEFAULT 1,
    priority INTEGER NOT NULL DEFAULT 5,
    explored_by_dream_id TEXT,
    owner_id TEXT NOT NULL DEFAULT 'default',
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);

CREATE INDEX IF NOT EXISTS idx_curiosity_seeds_active ON curiosity_seeds(active, source);
CREATE INDEX IF NOT EXISTS idx_curiosity_seeds_owner ON curiosity_seeds(owner_id);

-- Dream threading state (active threads, retired threads, steering notes)
CREATE TABLE IF NOT EXISTS dream_state (
    id TEXT PRIMARY KEY,
    owner_id TEXT NOT NULL DEFAULT 'default',
    thread_id TEXT NOT NULL,
    thread_title TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'active',
    depth_count INTEGER NOT NULL DEFAULT 0,
    last_dream_id TEXT,
    steering_notes TEXT,
    created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
    updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);

CREATE INDEX IF NOT EXISTS idx_dream_state_owner ON dream_state(owner_id, status);
CREATE INDEX IF NOT EXISTS idx_dream_state_thread ON dream_state(thread_id);
"""

SQL_DOWN = """
DROP TABLE IF EXISTS dreams;
DROP TABLE IF EXISTS curiosity_seeds;
DROP TABLE IF EXISTS dream_state;
"""


async def upgrade(conn) -> None:
    """Apply the migration."""
    await conn.executescript(SQL_UP)


async def downgrade(conn) -> None:
    """Revert the migration."""
    await conn.executescript(SQL_DOWN)
