-- 唱歌视频生成任务诊断SQL（正确的表名）

-- 注意：实际表名是 nf_generation_tasks，不是 generation_task

-- 1. 查看任务详情
SELECT 
    id, 
    user_id,
    lover_id,
    status, 
    error_msg, 
    JSON_PRETTY(payload) as payload_detail,
    created_at, 
    updated_at 
FROM nf_generation_tasks 
WHERE id = 382;

-- 2. 查看关联的分段视频状态
SELECT 
    sv.id as segment_video_id,
    sv.segment_id,
    sv.status,
    sv.error_msg,
    sv.dashscope_task_id,
    sv.video_url,
    ss.segment_index,
    ss.duration_ms,
    ss.audio_url
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 = 382
)
AND sv.image_hash = (
    SELECT JSON_EXTRACT(payload, '$.image_hash')
    FROM nf_generation_tasks
    WHERE id = 382
)
ORDER BY ss.segment_index;

-- 3. 查看用户剩余次数
SELECT 
    u.id,
    u.mobile,
    u.video_gen_remaining,
    u.image_gen_remaining,
    u.voice_call_minutes_remaining
FROM nf_user u
WHERE u.id = (
    SELECT user_id FROM nf_generation_tasks WHERE id = 382
);

-- 4. 查看歌曲信息
SELECT 
    sl.id,
    sl.title,
    sl.artist,
    sl.gender,
    sl.duration_sec,
    sl.audio_url,
    sl.audio_hash,
    sl.status
FROM nf_song_library sl
WHERE sl.id = (
    SELECT JSON_EXTRACT(payload, '$.song_id')
    FROM nf_generation_tasks
    WHERE id = 382
);

-- 5. 查看恋人信息
SELECT 
    l.id,
    l.name,
    l.gender,
    l.image_url,
    l.status
FROM nf_lover l
WHERE l.id = (
    SELECT lover_id FROM nf_generation_tasks WHERE id = 382
);

-- 6. 查看最近的失败任务（找出共性问题）
SELECT 
    id,
    user_id,
    status,
    error_msg,
    JSON_EXTRACT(payload, '$.song_id') as song_id,
    JSON_EXTRACT(payload, '$.song_title') as song_title,
    created_at
FROM nf_generation_tasks
WHERE status = 'failed'
AND task_type = 'video'
ORDER BY created_at DESC
LIMIT 10;

-- 7. 查看任务382附近的任务
SELECT 
    id,
    user_id,
    task_type,
    status,
    error_msg,
    created_at
FROM nf_generation_tasks
WHERE id BETWEEN 380 AND 390
ORDER BY id;
