<?php

namespace OtomaticAi\Controllers\SingleMode;

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

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

        $persona = Persona::find($this->input('persona_id'));

        if (empty($persona)) {
            $this->response(["message" => "An error occurred", "error" => "Unable to find the persona #" . $this->input("persona_id") . "."], 503);
        }

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

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

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

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