-- 检查卡住的任务（running状态超过一定时间）

-- 1. 查看所有running状态的任务
SELECT 
    id,
    user_id,
    lover_id,
    task_type,
    status,
    created_at,
    updated_at,
    TIMESTAMPDIFF(MINUTE, updated_at, NOW()) as minutes_stuck,
    JSON_EXTRACT(payload, '$.song_title') as song_title
FROM nf_generation_tasks
WHERE status = 'running'
ORDER BY created_at DESC;

-- 2. 查看任务385的详细信息
SELECT 
    id,
    status,
    error_msg,
    attempts,
    created_at,
    updated_at,
    TIMESTAMPDIFF(MINUTE, created_at, NOW()) as total_minutes,
    TIMESTAMPDIFF(MINUTE, updated_at, NOW()) as stuck_minutes
FROM nf_generation_tasks
WHERE id = 385\G

-- 3. 查看任务385的payload
SELECT JSON_PRETTY(payload) as payload_detail
FROM nf_generation_tasks
WHERE id = 385\G

-- 4. 查看任务385的分段视频状态
SELECT 
    sv.id,
    sv.segment_id,
    sv.status,
    sv.error_msg,
    sv.dashscope_task_id,
    sv.created_at,
    sv.updated_at,
    TIMESTAMPDIFF(MINUTE, sv.updated_at, NOW()) as stuck_minutes,
    ss.segment_index
FROM nf_song_segment_video sv
LEFT JOIN nf_song_segment ss ON sv.segment_id = ss.id
WHERE sv.song_id = (SELECT JSON_EXTRACT(payload, '$.song_id') FROM nf_generation_tasks WHERE id = 385)
AND sv.image_hash = (SELECT JSON_EXTRACT(payload, '$.image_hash') FROM nf_generation_tasks WHERE id = 385)
ORDER BY ss.segment_index;

-- 5. 强制标记超时任务为失败（超过30分钟的running任务）
-- 注意：这是修复操作，执行前请确认
/*
UPDATE nf_generation_tasks
SET 
    status = 'failed',
    error_msg = '任务超时（超过30分钟未完成）',
    updated_at = NOW()
WHERE status = 'running'
AND TIMESTAMPDIFF(MINUTE, updated_at, NOW()) > 30;
*/

-- 6. 查看最近1小时内的所有任务状态
SELECT 
    id,
    task_type,
    status,
    error_msg,
    created_at,
    TIMESTAMPDIFF(MINUTE, created_at, NOW()) as age_minutes
FROM nf_generation_tasks
WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)
ORDER BY id DESC;
