<?php

namespace OtomaticAi\Controllers;

use Exception;
use OtomaticAi\Models\Presets\Preset;
use OtomaticAi\Utils\DataSync;
use OtomaticAi\Vendors\Illuminate\Support\Arr;
use OtomaticAi\Vendors\Illuminate\Support\Str;

class TextBlocksController extends Controller
{
    public function index()
    {
        $this->verifyNonce();

        $this->response([
            "local" => [],
            "otomatic_ai" => $this->getOtomaticAITextBlocks(),
        ]);
    }

    public function generatePrompt()
    {
        $this->verifyNonce();

        $this->validate([
            "description" => ["required", "string"],
        ]);

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

            // run the preset
            $response = $preset->process([
                "content" => $this->input('description'),
            ]);

            // get the response content
            $content = Arr::get($response, 'choices.0.message.content');
            $content = Str::clean($content);

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

        $this->response([
            "prompt" => "",
        ]);
    }

    private function getOtomaticAITextBlocks()
    {
        return DataSync::getData("text_blocks", []);
    }
}
