<?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 KeywordsSourceController extends Controller
{
    public function search()
    {
        $this->validate([
            "keywords" => ["required", "string"],
            "language" => ["required", "string"],
        ]);

        $styles = ["informative", "commercial", "clickbait", "comparative"];

        try {
            // get the ai preset
            $preset = Preset::findFromAPI("generate_titles");

            // make payloads
            $payloads = [];
            foreach ($styles as $style) {
                $payloads[] = [
                    "language" => Language::find($this->input('language', 'en'))->value,
                    "length" => 5,
                    "style" => $style,
                    "request" => $this->input('keywords'),
                ];
            }

            // run the pool preset
            $responses = $preset->processPool($payloads);

            // get the response content
            $output = [];
            foreach ($responses as $index => $response) {
                $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);
                    }));
                    if (!empty($items)) {
                        $output[$styles[$index]] = [];
                        foreach ($items as $item) {
                            $output[$styles[$index]][] = [
                                "title" => $item,
                                "keywords" => $this->input('keywords'),
                            ];
                        }
                    }
                }
            }

            // reorder the output
            $_output = $output;
            $output = [];
            foreach ($styles as $style) {
                if (isset($_output[$style])) {
                    $output[$style] = $_output[$style];
                }
            }

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

        return [];
    }
}
