-- Migration: 004_add_telemetry
-- Author: Descomplicar®
-- Date: 2026-02-01
-- Description: Tabelas de telemetria e uso

-- UP

-- Uso de agentes
CREATE TABLE IF NOT EXISTS cr_agent_usage (
    id INT AUTO_INCREMENT PRIMARY KEY,
    agent_id INT NOT NULL,
    session_id VARCHAR(100),
    invocations INT DEFAULT 1,
    success_count INT DEFAULT 0,
    error_count INT DEFAULT 0,
    total_duration_ms INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (agent_id) REFERENCES cr_agents(id) ON DELETE CASCADE
);

-- Uso de skills
CREATE TABLE IF NOT EXISTS cr_skill_usage (
    id INT AUTO_INCREMENT PRIMARY KEY,
    skill_id INT NOT NULL,
    session_id VARCHAR(100),
    invocations INT DEFAULT 1,
    success_count INT DEFAULT 0,
    error_count INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (skill_id) REFERENCES cr_skills(id) ON DELETE CASCADE
);

-- Uso de ferramentas MCP
CREATE TABLE IF NOT EXISTS cr_mcp_tool_usage (
    id INT AUTO_INCREMENT PRIMARY KEY,
    mcp_id INT NOT NULL,
    tool_name VARCHAR(100) NOT NULL,
    session_id VARCHAR(100),
    invocations INT DEFAULT 1,
    success_count INT DEFAULT 0,
    error_count INT DEFAULT 0,
    avg_latency_ms INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (mcp_id) REFERENCES cr_mcps(id) ON DELETE CASCADE
);

-- Uso de LSPs
CREATE TABLE IF NOT EXISTS cr_lsp_usage (
    id INT AUTO_INCREMENT PRIMARY KEY,
    lsp_id INT NOT NULL,
    session_id VARCHAR(100),
    invocations INT DEFAULT 1,
    completions INT DEFAULT 0,
    diagnostics INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (lsp_id) REFERENCES cr_lsps(id) ON DELETE CASCADE
);

-- Índices para queries de telemetria
CREATE INDEX idx_agent_usage_date ON cr_agent_usage(created_at);
CREATE INDEX idx_agent_usage_agent ON cr_agent_usage(agent_id);
CREATE INDEX idx_skill_usage_date ON cr_skill_usage(created_at);
CREATE INDEX idx_skill_usage_skill ON cr_skill_usage(skill_id);
CREATE INDEX idx_mcp_tool_usage_date ON cr_mcp_tool_usage(created_at);
CREATE INDEX idx_mcp_tool_usage_mcp ON cr_mcp_tool_usage(mcp_id);
CREATE INDEX idx_lsp_usage_date ON cr_lsp_usage(created_at);

-- DOWN
DROP TABLE IF EXISTS cr_lsp_usage;
DROP TABLE IF EXISTS cr_mcp_tool_usage;
DROP TABLE IF EXISTS cr_skill_usage;
DROP TABLE IF EXISTS cr_agent_usage;
