-- =====================================================
-- LLM SCHEMA - MESSAGES TABLE
-- =====================================================
-- Description: Individual messages in conversations
-- Schema: llm
-- Author: Database Agent
-- Date: 2025-12-06
-- =====================================================

CREATE TABLE llm.messages (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Conversación
  conversation_id UUID NOT NULL REFERENCES llm.conversations(id) ON DELETE CASCADE,

  -- Rol y contenido
  role llm.message_role NOT NULL,
  content TEXT NOT NULL,

  -- Metadata de LLM
  model_name VARCHAR(100), -- claude-opus-4-5, gpt-4, etc.
  prompt_tokens INTEGER,
  completion_tokens INTEGER,
  total_tokens INTEGER,

  -- Contexto utilizado
  context_used JSONB, -- RAG context, market data, user profile, etc.

  -- Tools/Functions llamadas
  tool_calls JSONB, -- Function calls realizadas
  tool_results JSONB, -- Resultados de tool calls

  -- Metadata de procesamiento
  response_time_ms INTEGER,
  temperature DECIMAL(3,2),

  -- Feedback del usuario
  user_rating INTEGER CHECK (user_rating >= 1 AND user_rating <= 5),
  user_feedback TEXT,

  -- Referencias
  references_symbols VARCHAR(20)[] DEFAULT '{}',
  references_concepts TEXT[] DEFAULT '{}',

  -- Metadata
  metadata JSONB,

  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Índices
CREATE INDEX idx_messages_conversation ON llm.messages(conversation_id);
CREATE INDEX idx_messages_role ON llm.messages(role);
CREATE INDEX idx_messages_created ON llm.messages(created_at DESC);
CREATE INDEX idx_messages_conversation_created ON llm.messages(conversation_id, created_at ASC);
CREATE INDEX idx_messages_rated ON llm.messages(user_rating) WHERE user_rating IS NOT NULL;

-- Comentarios
COMMENT ON TABLE llm.messages IS 'Individual messages in LLM conversations';
COMMENT ON COLUMN llm.messages.role IS 'Message sender: user, assistant, system, or tool';
COMMENT ON COLUMN llm.messages.content IS 'Message text content';
COMMENT ON COLUMN llm.messages.model_name IS 'LLM model used to generate response';
COMMENT ON COLUMN llm.messages.context_used IS 'Context provided to LLM (RAG docs, market data, user profile)';
COMMENT ON COLUMN llm.messages.tool_calls IS 'Functions/tools called by LLM during response generation';
COMMENT ON COLUMN llm.messages.user_rating IS 'User satisfaction rating (1-5 stars)';

-- Ejemplo de context_used JSONB:
COMMENT ON COLUMN llm.messages.context_used IS
'Example: {
  "market_data": {
    "symbol": "BTCUSDT",
    "price": 45234.12,
    "change_24h": 0.0234
  },
  "user_profile": {
    "risk_profile": "moderate",
    "preferred_symbols": ["BTCUSDT", "ETHUSDT"]
  },
  "rag_documents": [
    {"doc_id": "123", "relevance": 0.89, "snippet": "..."},
    {"doc_id": "456", "relevance": 0.76, "snippet": "..."}
  ]
}';

-- Ejemplo de tool_calls JSONB:
COMMENT ON COLUMN llm.messages.tool_calls IS
'Example: [
  {
    "tool": "get_market_data",
    "params": {"symbol": "BTCUSDT", "timeframe": "1h"},
    "result": {...}
  },
  {
    "tool": "calculate_indicator",
    "params": {"indicator": "rsi", "period": 14},
    "result": {"rsi": 65.42}
  }
]';
