-- Compiled with roblox-ts v2.3.0
local TS = _G[script]
local HttpService = TS.import(script, TS.getModule(script, "@rbxts", "services")).HttpService
local AI_PROMPT = `You are acting as a UI library for Roblox.\
\
The following is a list of supported datatypes and the type that you must generate.\
Enums should be generated as strings, using the name of the EnumItem.\
\
Color3: \{ red: number, green: number, blue: number \}\
UDim2: \{ xScale: number, xOffset: number, yScale: number, yOffset: number \}\
UDim: \{ scale: number, offset: number \}\
Vector2: \{ x: number, y: number \}\
string: string\
number: number\
boolean: boolean\
\
All Roblox instance classes are supported, and should be generated in the following format:\
\{ className: string, properties: Record<string, DataType>, children: Array<Instance> \}\
\
The "properties" field specifies the properties that must be set and the value must be one of the supported datatypes, with a "type" field indicating the name of the datatype and a "value" field with the actual datatype.\
Ensure the types provided in the "properties" field have the same type as the field in the Roblox API.\
\
Please emit a JSON object detailing the UI and in the format of the Instance type.`
local function setupServerAi(apiKey, model, temperature)
	if model == nil then
		model = "gpt-3.5-turbo"
	end
	if temperature == nil then
		temperature = 0
	end
	local prompts = {}
	local remote = Instance.new("RemoteFunction")
	remote.Name = "rotypeuibolt_OpenAI"
	remote.Parent = game:GetService("ReplicatedStorage")
	local createPrompt = TS.async(function(prompt)
		local _prompt = prompt
		local existingPrompt = prompts[_prompt]
		if existingPrompt then
			return TS.await(existingPrompt)
		end
		local promise = TS.Promise.new(function(resolve)
			local request = HttpService:RequestAsync({
				Url = "https://api.openai.com/v1/chat/completions",
				Method = "POST",
				Body = HttpService:JSONEncode({
					model = model,
					temperature = temperature,
					response_format = {
						type = "json_object",
					},
					messages = { {
						role = "system",
						content = AI_PROMPT,
					}, {
						role = "user",
						content = prompt,
					} },
				}),
				Headers = {
					["Content-Type"] = "application/json",
					Authorization = `Bearer {apiKey}`,
				},
			})
			local response = HttpService:JSONDecode(request.Body)
			resolve(response.choices[1].message.content)
			print(`Received design for prompt: "{prompt}"`)
		end)
		local _prompt_1 = prompt
		prompts[_prompt_1] = promise
		return TS.await(promise)
	end)
	remote.OnServerInvoke = function(_player, prompt)
		local _prompt = prompt
		if not (type(_prompt) == "string") then
			return nil
		end
		return createPrompt(prompt):expect()
	end
end
return {
	setupServerAi = setupServerAi,
}
