-- ============================================================
-- V4: 为AI任务表添加图片参数支持（修复版）
-- 描述: 支持图生视频功能，允许用户上传参考图片
-- 作者: 1818AI  
-- 日期: 2025-10-20
-- ============================================================

-- 指定数据库
USE `1818ai`;

-- 1. 添加 image_url 字段（如果不存在）
SET @col_exists = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'ai_task' 
      AND COLUMN_NAME = 'image_url'
);

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE `ai_task` ADD COLUMN `image_url` VARCHAR(500) NULL COMMENT ''参考图片URL（用于图生视频）'' AFTER `prompt`',
    'SELECT ''Column image_url already exists'' AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 2. 添加 image_base64 字段（如果不存在）
SET @col_exists = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'ai_task' 
      AND COLUMN_NAME = 'image_base64'
);

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE `ai_task` ADD COLUMN `image_base64` TEXT NULL COMMENT ''参考图片Base64编码（用于图生视频）'' AFTER `image_url`',
    'SELECT ''Column image_base64 already exists'' AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 3. 添加 aspect_ratio 字段（如果不存在）
SET @col_exists = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'ai_task' 
      AND COLUMN_NAME = 'aspect_ratio'
);

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE `ai_task` ADD COLUMN `aspect_ratio` VARCHAR(10) NULL COMMENT ''图片宽高比（如2:3, 3:2, 1:1）'' AFTER `image_base64`',
    'SELECT ''Column aspect_ratio already exists'' AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 4. 添加索引（如果不存在）
SET @index_exists = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.STATISTICS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'ai_task' 
      AND INDEX_NAME = 'idx_task_type'
);

SET @sql = IF(@index_exists = 0,
    'CREATE INDEX `idx_task_type` ON `ai_task`(`task_type`)',
    'SELECT ''Index idx_task_type already exists'' AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 5. 验证字段是否添加成功
SELECT 
    COLUMN_NAME,
    COLUMN_TYPE,
    IS_NULLABLE,
    COLUMN_COMMENT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
  AND TABLE_NAME = 'ai_task'
  AND COLUMN_NAME IN ('image_url', 'image_base64', 'aspect_ratio')
ORDER BY ORDINAL_POSITION;

-- ============================================================
-- V4脚本结束
-- ============================================================

