-- Phase 4: Add language/voice/tokens columns to ai_conversations.
-- All non-destructive with defaults so this is safe on existing rows.

BEGIN;

-- 1. Detected language of the user message. 2-letter ISO code (en, es, fr,
--    de, hi, zh, ja, pt, ar, ru). Defaults to 'en' for back-compat.
ALTER TABLE ai_conversations
    ADD COLUMN IF NOT EXISTS language VARCHAR(8) NOT NULL DEFAULT 'en';

-- 2. Voice-input metadata: did this conversation come from a voice
--    transcript, and how long was the audio?
ALTER TABLE ai_conversations
    ADD COLUMN IF NOT EXISTS has_voice BOOLEAN NOT NULL DEFAULT FALSE,
    ADD COLUMN IF NOT EXISTS voice_duration_ms INTEGER;

-- 3. Context-window management: a rough char-based token estimate for the
--    query+response pair, plus a one-line LLM-generated summary that we can
--    splice in when the conversation gets long.
ALTER TABLE ai_conversations
    ADD COLUMN IF NOT EXISTS tokens_estimate INTEGER,
    ADD COLUMN IF NOT EXISTS summary TEXT;

-- Hot path: "all conversations in a given language for analytics"
CREATE INDEX IF NOT EXISTS idx_ai_conversations_language
    ON ai_conversations (language, created_at DESC);

-- Hot path: "find voice conversations"
CREATE INDEX IF NOT EXISTS idx_ai_conversations_voice
    ON ai_conversations (user_id, has_voice) WHERE has_voice = TRUE;

COMMIT;
