<?php

namespace OtomaticAi\Jobs;

use OtomaticAi\Models\ThumbnailTask;
use OtomaticAi\Modules\ProcessImageModule;
use OtomaticAi\Modules\ProcessThumbnailFinalizeModule;
use OtomaticAi\Utils\Analytics;
use OtomaticAi\Utils\Auth;
use OtomaticAi\Vendors\Illuminate\Support\Arr;
use Throwable;

class GenerateThumbnailJob extends Job
{
    private ThumbnailTask $thumbnailTask;

    /**
     * Create a new job instance.
     */
    public function __construct(ThumbnailTask $thumbnailTask)
    {
        $this->thumbnailTask = $thumbnailTask;
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
        try {
            // verify that the generation can be publish
            if (!$this->canPublish()) {
                return;
            }

            // clear generation logs
            $this->thumbnailTask->clearLogs();

            // set the generation status to pending
            $this->thumbnailTask->status = "pending";
            $this->thumbnailTask->save();

            // track the start of the job
            Analytics::trackEvent("generate-thumbnail-start", [
                "image_model" => Arr::get($this->thumbnailTask->modules, "models.image", 'dall-e-3'),
            ]);

            // make the generation modules
            $modules = [
                ProcessImageModule::class,
                ProcessThumbnailFinalizeModule::class,
            ];

            // set the generation state
            $generationState = [
                "version" => 1,
                "status" => "running",
                "current_step" => "process_image_module",
                "steps" => Arr::keyBy(Arr::values(Arr::whereNotNull(Arr::map($modules, function ($class) {
                    return [
                        "name" => $class::SLUG_NAME,
                        "status" => "idle",
                    ];
                }))), "name"),
                "artifacts" => [],
            ];

            // set the generation state
            $this->thumbnailTask->generation_state = $generationState;
            $this->thumbnailTask->save();

            // dispatch the first step
            ProcessPublicationStepJob::dispatch(["id" => $this->thumbnailTask->id, "model_class" => $this->thumbnailTask->getMorphClass()], 5);
        } catch (Throwable $e) {
            return $this->fail($e);
        }
    }

    private function canPublish()
    {
        // thumbnail task not started
        if ($this->thumbnailTask->status !== "idle") {
            return false;
        }

        // publication is published
        if ($this->thumbnailTask->publication->status !== "success") {
            return false;
        }

        // publication has post id
        if (empty($this->thumbnailTask->publication->post_id)) {
            return false;
        }

        // premium or trial
        if (!Auth::isPremium()) {
            return false;
        }

        // filter publications without thumbnail
        if (!$this->thumbnailTask->override) {
            // publication has thumbnail, skip
            if (has_post_thumbnail($this->thumbnailTask->publication->post_id)) {
                return false;
            }
        }

        return true;
    }

    private function fail(Throwable $error)
    {
        $this->thumbnailTask->addLog("Thumbnail task failed. " . $error->getMessage(), "_default", "error", $error->getTrace());

        // track the failure of the job
        Analytics::trackEvent("generate-thumbnail-failed", [
            "image_model" => Arr::get($this->thumbnailTask->modules, "models.image", 'dall-e-3'),
            "message" => $error->getMessage(),
        ]);

        $this->thumbnailTask->status = "failed";
        $this->thumbnailTask->save();
    }
}
