-- =====================================================
-- LLM SCHEMA - USER MEMORY TABLE
-- =====================================================
-- Description: Persistent memory about users for personalization
-- Schema: llm
-- Author: Database Agent
-- Date: 2025-12-06
-- =====================================================

CREATE TABLE llm.user_memory (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,

  -- Tipo de memoria
  memory_type llm.memory_type NOT NULL,

  -- Contenido
  key VARCHAR(200) NOT NULL,
  value TEXT NOT NULL,

  -- Importancia
  importance_score DECIMAL(3,2) DEFAULT 0.50 CHECK (importance_score >= 0.00 AND importance_score <= 1.00),

  -- Fuente
  source_conversation_id UUID REFERENCES llm.conversations(id) ON DELETE SET NULL,
  extracted_from TEXT, -- Fragmento del que se extrajo la memoria
  extraction_method VARCHAR(50) DEFAULT 'llm', -- llm, manual, system

  -- Validez
  is_active BOOLEAN DEFAULT true,
  expires_at TIMESTAMPTZ,

  -- Confirmación (algunas memorias pueden requerir confirmación del usuario)
  requires_confirmation BOOLEAN DEFAULT false,
  confirmed_by_user BOOLEAN DEFAULT false,
  confirmed_at TIMESTAMPTZ,

  -- Metadata
  metadata JSONB,

  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  -- Constraints
  CONSTRAINT unique_user_memory_key UNIQUE(user_id, memory_type, key)
);

-- Índices
CREATE INDEX idx_memory_user ON llm.user_memory(user_id);
CREATE INDEX idx_memory_type ON llm.user_memory(memory_type);
CREATE INDEX idx_memory_active ON llm.user_memory(is_active) WHERE is_active = true;
CREATE INDEX idx_memory_importance ON llm.user_memory(importance_score DESC);
CREATE INDEX idx_memory_conversation ON llm.user_memory(source_conversation_id);
CREATE INDEX idx_memory_expires ON llm.user_memory(expires_at) WHERE expires_at IS NOT NULL;

-- Comentarios
COMMENT ON TABLE llm.user_memory IS 'Persistent memory about users for LLM personalization and context';
COMMENT ON COLUMN llm.user_memory.memory_type IS 'Type of memory: fact, preference, context, goal, or constraint';
COMMENT ON COLUMN llm.user_memory.key IS 'Memory identifier (e.g., "favorite_symbol", "trading_goal", "risk_limit")';
COMMENT ON COLUMN llm.user_memory.value IS 'Memory content (e.g., "BTCUSDT", "save for house", "max 5% per trade")';
COMMENT ON COLUMN llm.user_memory.importance_score IS 'Importance weight (0.00-1.00) for retrieval prioritization';
COMMENT ON COLUMN llm.user_memory.extracted_from IS 'Original text from which memory was extracted';
COMMENT ON COLUMN llm.user_memory.requires_confirmation IS 'Whether this memory needs explicit user confirmation';

-- Ejemplos de memorias por tipo:
COMMENT ON COLUMN llm.user_memory.memory_type IS
'Memory type examples:
- fact: "trading_since" = "2020", "max_loss_experienced" = "15%"
- preference: "favorite_indicator" = "RSI", "avoids_margin_trading" = "true"
- context: "recent_portfolio_loss" = "trying to recover", "learning_focus" = "risk management"
- goal: "monthly_target" = "5% return", "learning_goal" = "master technical analysis"
- constraint: "max_risk_per_trade" = "2%", "no_trading_during_work" = "9am-5pm"';

-- Ejemplo de metadata JSONB:
COMMENT ON COLUMN llm.user_memory.metadata IS
'Example: {
  "confidence": 0.85,
  "last_mentioned": "2025-12-05T10:30:00Z",
  "mention_count": 5,
  "related_memories": ["mem_123", "mem_456"],
  "tags": ["trading_style", "risk_management"]
}';
