<?php

namespace OtomaticAi\Modules;

use Exception;
use OtomaticAi\Models\Contracts\Publishable;
use OtomaticAi\Models\Presets\Preset;
use OtomaticAi\Modules\Contracts\Module as ModuleContract;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class ProcessCustomFieldsModule extends Module implements ModuleContract
{
    const SLUG_NAME = "process_custom_fields_module";

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

        $items = [];
        foreach ($this->getModuleValue("wordpress.custom_fields", []) as $customField) {
            $key = Arr::get($customField, "key");
            $value = Arr::get($customField, "value");

            if (empty($key)) {
                continue;
            }

            if (Arr::get($customField, "is_prompt", false)) {
                if (empty($value)) {
                    continue;
                }

                try {
                    $preset = Preset::make([
                        "model" => 'gpt-4o-mini',
                        "messages" => [
                            [
                                "role" => "user",
                                "content" => $value,
                            ]
                        ],
                    ]);

                    // run the preset
                    $response = $preset->process([
                        "language" => $this->getLanguage()->value,
                        "title" => $this->getTitle(),
                        "request" => $this->getTitle(),
                    ]);

                    // get the response content
                    $value = Arr::get($response, 'choices.0.message.content');
                } catch (Exception $e) {
                    continue;
                }
            }

            $items[] = [
                "key" =>  $key,
                "value" =>  $value,
            ];
        }

        // add custom fields to the generation state
        if (count($items) > 0) {
            $this->generationState->setArtifact("custom_fields", $items);
        }
    }

    /**
     * Determine if the module is runnable
     *
     * @return boolean
     */
    public function isRunnable(): bool
    {
        // must have custom fields
        if (count($this->getModuleValue("wordpress.custom_fields", [])) === 0) {
            return false;
        }

        return true;
    }

    static public function isEnabled(Publishable $publishable): bool
    {
        if (count(self::getPublicationModuleValue($publishable, "wordpress.custom_fields", [])) === 0) {
            return false;
        }

        return true;
    }
}
