<?php

namespace App\Console\Commands;

use App\Services\AIGeneration\AIImageGenerationService;
use Illuminate\Console\Command;

class ProcessImageGenerationQueueCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'image-generation:process-queue';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '处理图片生成任务队列，检查任务状态并处理下一个排队任务';

    private $imageGenerationService;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(AIImageGenerationService $imageGenerationService)
    {
        parent::__construct();
        $this->imageGenerationService = $imageGenerationService;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('开始处理图片生成任务队列...');

        try {
            // 更新所有待处理任务的状态
            $this->imageGenerationService->updatePendingTasks();
            
            // 获取队列状态
            $queueStatus = $this->imageGenerationService->getQueueStatus();
            
            $this->info("队列状态: 处理中任务数: {$queueStatus['processing_count']}, 排队任务数: {$queueStatus['pending_count']}");
            
            if ($queueStatus['can_submit_new_task'] && $queueStatus['pending_count'] > 0) {
                $this->info('开始处理下一个排队任务...');
                $this->imageGenerationService->processNextQueuedTask();
            }
            
            $this->info('任务队列处理完成');
            return 0;
        } catch (\Exception $e) {
            $this->error('处理任务队列时发生错误: ' . $e->getMessage());
            return 1;
        }
    }
}