<?php

namespace OtomaticAi\Modules;

use Exception;
use OtomaticAi\Content\Image\Image;
use OtomaticAi\Models\Contracts\Publishable;
use OtomaticAi\Modules\Contracts\Module as ModuleContract;
use OtomaticAi\Utils\Analytics;

class ProcessThumbnailFinalizeModule extends Module implements ModuleContract
{
    const SLUG_NAME = "process_thumbnail_finalize_module";

    /**
     * Execute the job.
     *
     * @return void
     * @throws Exception
     */
    public function handle(): void
    {
        // verify that the job is runnable
        if (!$this->isRunnable()) {
            return;
        }

        // log the start of the job
        $this->publication->addLog("Finalize module started.", self::SLUG_NAME);

        // get the thumbnail from the extras
        $saved = false;
        if (($image = $this->generationState->getArtifact('thumbnail')) !== null) {
            $image = Image::fromArray($image);
            if ($image !== null) {
                if (($attachmentId = $image->image->save($this->publication->publication->title, $image->description, $image->legend)) !== null) {
                    if (set_post_thumbnail($this->publication->publication->post_id, $attachmentId) === false) {
                        $this->publication->addLog("Unable to save the post thumbnail.", self::SLUG_NAME, "warning");
                    } else {
                        $saved = true;
                    }
                }
            }
        }

        if (!$saved) {
            $this->fail(new Exception("No thumbnail generated"));
        }

        // add the content to the publication
        $this->publication->status = "success";
        $this->publication->save();

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

        // log the end of the job
        $this->publication->addLog("Finalize module completed successfully.", self::SLUG_NAME, "success");
    }

    /**
     * Determine if the module is runnable
     *
     * @return boolean
     */
    public function isRunnable(): bool
    {
        return true;
    }

    static public function isEnabled(Publishable $publishable): bool
    {
        return true;
    }
}
