-- ============================================================================
-- Coze API调用记录表优化迁移脚本
-- 执行时间: 2025-07-13
-- 说明: 为coze_api_call表添加新字段以完整保存接口调用详情
-- ============================================================================

USE emotion_museum;

-- 备份现有数据（可选）
-- CREATE TABLE coze_api_call_backup AS SELECT * FROM coze_api_call;

-- 添加用户消息相关字段
ALTER TABLE coze_api_call 
ADD COLUMN user_message TEXT COMMENT '用户输入的消息内容' AFTER request_headers,
ADD COLUMN user_message_type VARCHAR(20) DEFAULT 'text' COMMENT '用户消息类型: text/image/file' AFTER user_message;

-- 添加AI回复相关字段
ALTER TABLE coze_api_call 
ADD COLUMN ai_reply TEXT COMMENT 'AI回复的消息内容' AFTER user_message_type,
ADD COLUMN ai_reply_type VARCHAR(20) DEFAULT 'text' COMMENT 'AI回复类型: text/image/file' AFTER ai_reply;

-- 添加轮询相关字段
ALTER TABLE coze_api_call 
ADD COLUMN poll_count INT DEFAULT 0 COMMENT '轮询次数' AFTER response_headers,
ADD COLUMN poll_start_time DATETIME COMMENT '轮询开始时间' AFTER poll_count,
ADD COLUMN poll_end_time DATETIME COMMENT '轮询结束时间' AFTER poll_start_time,
ADD COLUMN final_status VARCHAR(20) COMMENT '最终状态: completed/failed/timeout' AFTER poll_end_time;

-- 添加功能调用相关字段
ALTER TABLE coze_api_call 
ADD COLUMN function_calls JSON COMMENT '函数调用记录' AFTER total_tokens,
ADD COLUMN function_results JSON COMMENT '函数调用结果' AFTER function_calls;

-- 添加扩展信息字段
ALTER TABLE coze_api_call 
ADD COLUMN client_ip VARCHAR(45) COMMENT '客户端IP' AFTER error_message,
ADD COLUMN user_agent TEXT COMMENT '用户代理' AFTER client_ip,
ADD COLUMN session_id VARCHAR(100) COMMENT '会话ID' AFTER user_agent,
ADD COLUMN trace_id VARCHAR(100) COMMENT '追踪ID' AFTER session_id,
ADD COLUMN metadata JSON COMMENT '扩展元数据' AFTER trace_id;

-- 添加新字段的索引
CREATE INDEX idx_coze_api_call_final_status ON coze_api_call (final_status);
CREATE INDEX idx_coze_api_call_client_ip ON coze_api_call (client_ip);
CREATE INDEX idx_coze_api_call_session_id ON coze_api_call (session_id);
CREATE INDEX idx_coze_api_call_trace_id ON coze_api_call (trace_id);
CREATE INDEX idx_coze_api_call_user_status ON coze_api_call (user_id, status);
CREATE INDEX idx_coze_api_call_conversation_time ON coze_api_call (conversation_id, start_time);

-- 更新表注释
ALTER TABLE coze_api_call COMMENT = 'Coze API调用记录表 - 完整版本';

-- 验证表结构
DESCRIBE coze_api_call;

-- 显示表的索引
SHOW INDEX FROM coze_api_call;

-- 统计现有数据
SELECT 
    COUNT(*) as total_records,
    COUNT(DISTINCT user_id) as unique_users,
    COUNT(DISTINCT conversation_id) as unique_conversations,
    MIN(create_time) as earliest_record,
    MAX(create_time) as latest_record
FROM coze_api_call;

-- 显示各状态的记录数
SELECT status, COUNT(*) as count 
FROM coze_api_call 
GROUP BY status;

COMMIT;

-- ============================================================================
-- 迁移完成
-- ============================================================================
