<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Artwork;
use App\Services\Maturity\ArtworkMaturityService;
use App\Services\Vision\VisionService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

final class DetectArtworkMaturityJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $tries = 3;

    public int $timeout = 20;

    public function __construct(
        private readonly int $artworkId,
        private readonly string $hash,
    ) {
        $queue = (string) config('maturity.ai.queue', config('vision.queue', 'default'));
        if ($queue !== '') {
            $this->onQueue($queue);
        }
    }

    public function backoff(): array
    {
        return [5, 30, 120];
    }

    public function handle(VisionService $vision, ArtworkMaturityService $maturity): void
    {
        if (! $vision->isEnabled()) {
            return;
        }

        $artwork = Artwork::query()->with(['categories.contentType'])->find($this->artworkId);
        if (! $artwork) {
            return;
        }

        $detailed = $vision->analyzeArtworkMaturityDetailed($artwork, $this->hash);
        $assessment = (array) ($detailed['assessment'] ?? []);
        if ($assessment === []) {
            $assessment = [
                'status' => ArtworkMaturityService::AI_STATUS_FAILED,
                'advisory' => 'Vision maturity analysis returned no assessment payload.',
            ];
        }

        $maturity->applyAiAssessment($artwork->fresh(), $assessment);
    }

    public function failed(\Throwable $exception): void
    {
        $artwork = Artwork::query()->find($this->artworkId);
        if ($artwork) {
            app(ArtworkMaturityService::class)->applyAiAssessment($artwork, [
                'status' => ArtworkMaturityService::AI_STATUS_FAILED,
                'advisory' => $exception->getMessage(),
            ]);
        }

        Log::warning('DetectArtworkMaturityJob failed', [
            'artwork_id' => $this->artworkId,
            'hash' => $this->hash,
            'error' => $exception->getMessage(),
        ]);
    }
}