<?php

namespace App\Console\Commands;

use App\Services\AIGeneration\AIImageGenerationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Consts\BaseConst;

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

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

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

        // 执行50s
        $time_start = time();
        try {
            // 统计需要处理的任务数量（即梦AI的processing + 火山API的pending和processing）
            $jimengProcessingCount = DB::table('mp_generate_pic_tasks')
                ->where('status', 'processing')
                ->where('model', 'jimeng_4.0')
                ->count('id');
            
            $volcPendingCount = DB::table('mp_generate_pic_tasks')
                ->where('status', 'pending')
                ->whereIn('model', BaseConst::VOLC_PIC_MODELS)
                ->count('id');
            
            $totalCount = $jimengProcessingCount + $volcPendingCount;
            
            dLog('generate')->info("待处理任务统计 - 即梦AI处理中: {$jimengProcessingCount}, 火山API待处理: {$volcPendingCount}");
            
            while ($totalCount > 0) {
                $time_diff = time() - $time_start;
                if ($time_diff > 50) {
                    dLog('generate')->info('定时任务执行超过50秒，退出循环');
                    break;
                }
                
                sleep(3);
                
                // 执行任务更新
                $aiImageGenerationService->updatePendingTasks();
                
                // 重新统计任务数量
                $jimengProcessingCount = DB::table('mp_generate_pic_tasks')
                    ->where('status', 'processing')
                    ->where('model', 'jimeng_4.0')
                    ->count('id');
                
                $volcPendingCount = DB::table('mp_generate_pic_tasks')
                    ->where('status', 'pending')
                    ->whereIn('model', BaseConst::VOLC_PIC_MODELS)
                    ->count('id');
                
                $totalCount = $jimengProcessingCount + $volcPendingCount;
            }
            
            dLog('generate')->info('任务状态检查完成');
            
            // 更新分镜表中的图片任务状态
            $this->updateSegmentPicStatus();
            
        } catch (\Exception $e) {
            dLog('generate')->error('任务状态检查失败: ' . $e->getMessage());
            return 1;
        }

        return 0;
    }

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

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

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

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

            foreach ($segments as $segment) {
                $picTaskId = $segment->pic_task_id;
                $segmentId = $segment->segment_id;

                // 查询图片生成任务状态
                $picTask = DB::table('mp_generate_pic_tasks')
                    ->where('id', $picTaskId)
                    ->select('id', 'status', 'result_url', 'error_message')
                    ->first();

                if (!$picTask) {
                    dLog('generate')->warning('分镜关联的图片任务不存在', [
                        'segment_id' => $segmentId,
                        'pic_task_id' => $picTaskId
                    ]);
                    continue;
                }

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

                // 根据任务状态更新分镜表
                if ($picTask->status === 'success') {
                    $updateData['pic_task_status'] = '已完成';
                    
                    // 处理 result_url（可能是JSON数组或字符串）
                    $resultUrl = $picTask->result_url;
                    if (is_string($resultUrl) && is_json($resultUrl)) {
                        $resultUrls = json_decode($resultUrl, true);
                        $updateData['img_url'] = is_array($resultUrls) ? $resultUrls[0] : $resultUrl;
                    } else {
                        $updateData['img_url'] = $resultUrl;
                    }
                    
                    $successCount++;
                    
                    dLog('generate')->info('分镜图片生成成功', [
                        'segment_id' => $segmentId,
                        'pic_task_id' => $picTaskId,
                        'img_url' => $updateData['img_url']
                    ]);
                    
                } elseif ($picTask->status === 'failed') {
                    $updateData['pic_task_status'] = '失败';
                    
                    $failedCount++;
                    
                    dLog('generate')->error('分镜图片生成失败', [
                        'segment_id' => $segmentId,
                        'pic_task_id' => $picTaskId,
                        'error' => $picTask->error_message
                    ]);
                    logDB('generate', 'error', '分镜图片生成失败', [
                        'segment_id' => $segmentId,
                        'pic_task_id' => $picTaskId,
                        'error' => $picTask->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()
            ]);
        }
    }
}