<?php

namespace OtomaticAi\Modules;

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

class ProcessSingleModeFinalizeModule extends Module implements ModuleContract
{
    const SLUG_NAME = "process_single_mode_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);

        // remove remaining placeholders
        $xpath = new DOMXPath($this->html);
        $nodes = $xpath->query("//placeholder");
        foreach ($nodes as $node) {
            $node->parentNode->removeChild($node);
        }

        // make content
        $content = trim(preg_replace("/^<body>|<\/body>$/", "", $this->html->saveHTML($this->html->getElementsByTagName("body")->item(0))));

        // encode emojis with wordpress
        $content = wp_encode_emoji($content);

        // quit if no content generated
        if (empty($content)) {
            throw new Exception("No content generated");
        }

        // get the extras
        $extras = $this->publication->extras ?? [];

        // add artifacts to extras, except html_content
        foreach ($this->generationState->getArtifacts() as $key => $value) {
            if ($key !== "html_content") {
                $extras[$key] = $value;
            }
        }
        $this->publication->extras = $extras;

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

        // track the end of the job
        Analytics::trackEvent("generate-single-mode-end", [
            "title" => $this->getTitle(),
            "type" => $this->getType(),
            "model" => $this->getModuleValue("models.text", 'gpt-4o-mini'),
            "image_model" => $this->getModuleValue("models.image", 'dall-e-3'),
            "is_automatic_mode" => $this->getModuleValue("content.automatic.enabled", false),
        ]);

        // 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;
    }
}
