<?php

namespace App\Console\Commands;

use App\Services\AIGeneration\AIVideoGenerationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CheckVideoGenerationTasksCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'AIGeneration:checkVideoTasks';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查视频生成任务状态并更新结果';

    /**
     * Execute the console command.
     *
     * @param AIVideoGenerationService $videoGenerationService
     * @return int
     */
    public function handle(AIVideoGenerationService $videoGenerationService)
    {
        dLog('generate')->info('开始检查视频生成任务状态...');

        // 执行50s
        $time_start = time();
        try {
            $count = DB::table('mp_generate_video_tasks')->where('status', 'processing')->count('id');
            while ($count > 0) {
                $time_diff = time() - $time_start;
                sleep(3);
                if ($time_diff > 50) break;
                $videoGenerationService->updatePendingTasks();
                $count = DB::table('mp_generate_video_tasks')->where('status', 'processing')->count('id');
            }
            
            // 更新分镜表中的视频任务状态
            $this->updateSegmentVideoStatus();
            
            dLog('generate')->info('视频任务状态检查完成');
        } catch (\Exception $e) {
            dLog('generate')->error('视频任务状态检查失败: ' . $e->getMessage());
            logDB('generate', 'error', '定时任务：视频生成任务状态检查失败', ['error' => $e->getMessage()]);
            return 1;
        }

        return 0;
    }

    /**
     * 更新分镜表中的视频任务状态
     * 
     * @return void
     */
    private function updateSegmentVideoStatus()
    {
        try {
            // 获取所有状态为"生成中"的分镜
            $segments = DB::table('mp_episode_segments')
                ->where('video_task_status', '生成中')
                ->whereNotNull('video_task_id')
                ->where('video_task_id', '<>', '')
                ->select('segment_id', 'video_task_id')
                ->get();

            if ($segments->isEmpty()) {
                return;
            }

            dLog('generate')->info('开始更新分镜视频任务状态', ['count' => $segments->count()]);

            $successCount = 0;
            $failedCount = 0;
            $processingCount = 0;

            foreach ($segments as $segment) {
                $videoTaskId = $segment->video_task_id;
                $segmentId = $segment->segment_id;

                // 查询视频生成任务状态
                $videoTask = DB::table('mp_generate_video_tasks')
                    ->where('id', $videoTaskId)
                    ->select('id', 'status', 'result_url', 'last_frame_url', 'error_message')
                    ->first();

                if (!$videoTask) {
                    dLog('generate')->warning('分镜关联的视频任务不存在', [
                        'segment_id' => $segmentId,
                        'video_task_id' => $videoTaskId
                    ]);
                    continue;
                }

                $updateData = ['updated_at' => date('Y-m-d H:i:s')];

                // 根据任务状态更新分镜表
                if ($videoTask->status === 'success') {
                    $updateData['video_task_status'] = '已完成';
                    $updateData['video_url'] = $videoTask->result_url;
                    
                    // 如果有尾帧图片，也更新
                    if (!empty($videoTask->last_frame_url)) {
                        $updateData['last_frame_url'] = $videoTask->last_frame_url;
                    }
                    
                    $successCount++;
                    
                    dLog('generate')->info('分镜视频生成成功', [
                        'segment_id' => $segmentId,
                        'video_task_id' => $videoTaskId,
                        'video_url' => $videoTask->result_url
                    ]);
                    
                } elseif ($videoTask->status === 'failed') {
                    $updateData['video_task_status'] = '失败';
                    
                    $failedCount++;
                    
                    dLog('generate')->error('分镜视频生成失败', [
                        'segment_id' => $segmentId,
                        'video_task_id' => $videoTaskId,
                        'error' => $videoTask->error_message
                    ]);
                    logDB('generate', 'error', '分镜视频生成失败', [
                        'segment_id' => $segmentId,
                        'video_task_id' => $videoTaskId,
                        'error' => $videoTask->error_message
                    ]);
                    
                } else {
                    // 仍在处理中，不更新
                    $processingCount++;
                    continue;
                }

                // 更新分镜表
                DB::table('mp_episode_segments')
                    ->where('segment_id', $segmentId)
                    ->update($updateData);
            }

            dLog('generate')->info('分镜视频任务状态更新完成', [
                'total' => $segments->count(),
                'success' => $successCount,
                'failed' => $failedCount,
                'processing' => $processingCount
            ]);

        } catch (\Exception $e) {
            dLog('generate')->error('更新分镜视频任务状态异常: ' . $e->getMessage());
            logDB('generate', 'error', '更新分镜视频任务状态异常', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }
}