-- 回滚：恢复video_classification_records表到旧的结构
-- 注意：这个回滚会丢失新字段的数据

-- 备份当前数据
CREATE TABLE video_classification_records_new_backup AS 
SELECT * FROM video_classification_records;

-- 删除新表
DROP TABLE video_classification_records;

-- 重新创建旧的video_classification_records表结构
CREATE TABLE IF NOT EXISTS video_classification_records (
    id TEXT PRIMARY KEY,
    segment_id TEXT NOT NULL,
    classification_result TEXT,
    confidence_score REAL,
    processing_status TEXT NOT NULL DEFAULT 'Pending',
    processed_at DATETIME,
    error_message TEXT,
    gemini_response TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (segment_id) REFERENCES material_segments (id) ON DELETE CASCADE
);

-- 尝试迁移回旧格式的数据
INSERT INTO video_classification_records (
    id, segment_id, classification_result, confidence_score, processing_status,
    error_message, gemini_response, created_at, updated_at
)
SELECT 
    id,
    segment_id,
    category,  -- 使用category作为classification_result
    confidence,  -- 使用confidence作为confidence_score
    CASE 
        WHEN status = '"Classified"' THEN 'Completed'
        WHEN status = '"Failed"' THEN 'Failed'
        ELSE 'Pending'
    END,
    error_message,
    raw_response,  -- 使用raw_response作为gemini_response
    created_at,
    updated_at
FROM video_classification_records_new_backup
WHERE EXISTS (SELECT 1 FROM video_classification_records_new_backup);

-- 删除备份表
DROP TABLE video_classification_records_new_backup;

-- 重新创建旧的索引
CREATE INDEX IF NOT EXISTS idx_video_classification_records_segment_id ON video_classification_records (segment_id);
CREATE INDEX IF NOT EXISTS idx_video_classification_records_status ON video_classification_records (processing_status);
CREATE INDEX IF NOT EXISTS idx_video_classification_records_result ON video_classification_records (classification_result);
