<?php

namespace OtomaticAi\Controllers\SingleMode;

use Exception;
use OtomaticAi\Controllers\Controller;
use OtomaticAi\Models\Presets\Preset;
use OtomaticAi\Utils\Language;
use OtomaticAi\Vendors\Illuminate\Support\Arr;
use OtomaticAi\Vendors\Illuminate\Support\Str;

class GenerateKeywordsController extends Controller
{
    public function __invoke()
    {
        $this->validate([
            "title" => ["required", "string"],
            "language" => ["required", "string"],
        ]);

        try {
            // get the openai preset
            $preset = Preset::findFromAPI("generate_seo_keywords");


            // run the preset
            $response = $preset->process([
                "language" => Language::find($this->input('language', 'en'))->value,
                "title" => $this->input('title'),
            ]);

            // get the response content
            $output = [];
            $response = json_decode(Arr::get($response, 'choices.0.message.content'), true, 512, JSON_THROW_ON_ERROR);
            $items = Arr::get($response, "values");
            if (!empty($items)) {
                $items = array_map(function ($str) {
                    return Str::clean($str);
                }, $items);
                $items = array_values(array_filter($items, function ($str) {
                    return !empty($str);
                }));
                foreach ($items as $item) {
                    $output[] = $item;
                }
            }

            $this->response(["keywords" => $output]);
        } catch (Exception $e) {
            $this->response(["message" => "An error occurred", "error" => $e->getMessage()], 503);
        }
    }
}
