--[[
	PlayCrafter - Roblox Studio plugin
	Imports the scripts from your latest PlayCrafter build straight into your game.

	Install: save this file into your Studio Plugins folder
	(Studio > Plugins tab > Plugins Folder), then restart Studio.
]]

local BASE_URL = "https://playcrafterai.com"

local HttpService = game:GetService("HttpService")
local ChangeHistoryService = game:GetService("ChangeHistoryService")
local ScriptEditorService = game:GetService("ScriptEditorService")
local Selection = game:GetService("Selection")
local RunService = game:GetService("RunService")

local POLL_SECONDS = 4 -- how often auto-import checks for new builds

local SCRIPT_CLASSES = { Script = true, LocalScript = true, ModuleScript = true }

---------------------------------------------------------------------------
-- UI
---------------------------------------------------------------------------

local toolbar = plugin:CreateToolbar("PlayCrafter")
local toggleButton = toolbar:CreateButton("PlayCrafter", "Import your PlayCrafter scripts", "")
toggleButton.ClickableWhenViewportHidden = true

local widget = plugin:CreateDockWidgetPluginGui(
	"PlayCrafterImporter",
	DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Right, false, false, 320, 340, 260, 260)
)
widget.Title = "PlayCrafter"

local theme = settings().Studio.Theme
local function color(name)
	return theme:GetColor(Enum.StudioStyleGuideColor[name])
end

local root = Instance.new("ScrollingFrame")
root.Size = UDim2.fromScale(1, 1)
root.BorderSizePixel = 0
root.ScrollBarThickness = 6
root.AutomaticCanvasSize = Enum.AutomaticSize.Y
root.CanvasSize = UDim2.new()
root.Parent = widget

local padding = Instance.new("UIPadding")
padding.PaddingTop = UDim.new(0, 12)
padding.PaddingBottom = UDim.new(0, 12)
padding.PaddingLeft = UDim.new(0, 12)
padding.PaddingRight = UDim.new(0, 12)
padding.Parent = root

local layout = Instance.new("UIListLayout")
layout.Padding = UDim.new(0, 8)
layout.SortOrder = Enum.SortOrder.LayoutOrder
layout.Parent = root

local order = 0
local function label(text, bold)
	order += 1
	local l = Instance.new("TextLabel")
	l.LayoutOrder = order
	l.Size = UDim2.new(1, 0, 0, 0)
	l.AutomaticSize = Enum.AutomaticSize.Y
	l.BackgroundTransparency = 1
	l.TextWrapped = true
	l.TextXAlignment = Enum.TextXAlignment.Left
	l.Font = bold and Enum.Font.SourceSansBold or Enum.Font.SourceSans
	l.TextSize = bold and 18 or 15
	l.Text = text
	l.Parent = root
	return l
end

local function button(text, primary)
	order += 1
	local b = Instance.new("TextButton")
	b.LayoutOrder = order
	b.Size = UDim2.new(1, 0, 0, 34)
	b.Font = Enum.Font.SourceSansBold
	b.TextSize = 16
	b.Text = text
	b.AutoButtonColor = true
	b.BorderSizePixel = 0
	b:SetAttribute("Primary", primary == true)
	local corner = Instance.new("UICorner")
	corner.CornerRadius = UDim.new(0, 6)
	corner.Parent = b
	b.Parent = root
	return b
end

label("PlayCrafter", true)
local help = label("Build a game on the PlayCrafter website, then click Import to put every script into this place.")

local codeLabel = label("Connect code (from the website's Studio plugin page):")
order += 1
local codeBox = Instance.new("TextBox")
codeBox.LayoutOrder = order
codeBox.Size = UDim2.new(1, 0, 0, 30)
codeBox.ClearTextOnFocus = false
codeBox.PlaceholderText = "pcr_..."
codeBox.Text = ""
codeBox.Font = Enum.Font.Code
codeBox.TextSize = 14
codeBox.TextXAlignment = Enum.TextXAlignment.Left
codeBox.BorderSizePixel = 0
local boxPad = Instance.new("UIPadding")
boxPad.PaddingLeft = UDim.new(0, 6)
boxPad.Parent = codeBox
codeBox.Parent = root

local connectButton = button("Connect", false)
local importButton = button("Import latest build", true)
local autoButton = button("Auto-import: ON", false)
local statusLabel = label("")
local disconnectButton = button("Disconnect", false)

local function applyTheme()
	root.BackgroundColor3 = color("MainBackground")
	root.ScrollBarImageColor3 = color("ScrollBar")
	for _, child in root:GetChildren() do
		if child:IsA("TextLabel") then
			child.TextColor3 = color("MainText")
		elseif child:IsA("TextBox") then
			child.BackgroundColor3 = color("InputFieldBackground")
			child.TextColor3 = color("MainText")
			child.PlaceholderColor3 = color("DimmedText")
		elseif child:IsA("TextButton") then
			if child:GetAttribute("Primary") then
				child.BackgroundColor3 = Color3.fromRGB(74, 222, 128)
				child.TextColor3 = Color3.fromRGB(6, 33, 15)
			else
				child.BackgroundColor3 = color("Button")
				child.TextColor3 = color("ButtonText")
			end
		end
	end
end
applyTheme()
settings().Studio.ThemeChanged:Connect(function()
	theme = settings().Studio.Theme
	applyTheme()
end)

local function setStatus(text, isError)
	statusLabel.Text = text
	statusLabel.TextColor3 = isError and color("ErrorText") or color("MainText")
end

---------------------------------------------------------------------------
-- Talking to the website
---------------------------------------------------------------------------

local function getToken()
	return plugin:GetSetting("ConnectCode")
end

local function fetchJSON(token, path)
	local ok, response = pcall(function()
		return HttpService:RequestAsync({
			Url = BASE_URL .. path,
			Method = "GET",
			Headers = { Authorization = "Bearer " .. token },
		})
	end)
	if not ok then
		return nil, "Couldn't reach PlayCrafter. If Studio asked to allow HTTP requests for this plugin, click Allow and try again.\n(" .. tostring(response) .. ")"
	end
	if response.StatusCode == 401 then
		return nil, "That connect code isn't valid any more. Get a new one on the website."
	end
	if response.StatusCode == 402 then
		return nil, "The Studio plugin needs an active PlayCrafter Pro subscription. Renew on the website, then try again."
	end
	if not response.Success then
		return nil, "PlayCrafter server error (" .. response.StatusCode .. "). Try again in a moment."
	end
	local decoded, data = pcall(HttpService.JSONDecode, HttpService, response.Body)
	if not decoded then
		return nil, "Got an unexpected reply from the server."
	end
	return data
end

local function fetchLatest(token)
	return fetchJSON(token, "/api/plugin/latest")
end

---------------------------------------------------------------------------
-- Inserting scripts
---------------------------------------------------------------------------

local function splitPath(path)
	local parts = {}
	for part in string.gmatch(path, "[^/]+") do
		table.insert(parts, part)
	end
	return parts
end

-- Finds (or creates as Folders) every container in the path, starting from a service.
local function getContainer(parts)
	local ok, parent = pcall(game.GetService, game, parts[1])
	if not ok or not parent then
		return nil
	end
	for i = 2, #parts - 1 do
		local child = parent:FindFirstChild(parts[i])
		if not child then
			child = Instance.new("Folder")
			child.Name = parts[i]
			child.Parent = parent
		end
		parent = child
	end
	return parent
end

local function setSource(scriptObject, source)
	-- UpdateSourceAsync also works while the script is open in the editor
	local ok = pcall(function()
		ScriptEditorService:UpdateSourceAsync(scriptObject, function()
			return source
		end)
	end)
	if not ok then
		scriptObject.Source = source
	end
end

local function importScripts(scripts, keepSelection)
	local recording = ChangeHistoryService:TryBeginRecording("Import PlayCrafter build")
	local created, updated, skipped = 0, 0, {}
	local inserted = {}

	for _, info in scripts do
		local parts = splitPath(info.path)
		local name = parts[#parts]
		local container = #parts >= 2 and SCRIPT_CLASSES[info.className] and getContainer(parts)
		if not container then
			table.insert(skipped, info.path)
			continue
		end

		local existing = container:FindFirstChild(name)
		if existing and existing.ClassName ~= info.className then
			existing:Destroy() -- e.g. a Script that should now be a LocalScript (Ctrl+Z restores it)
			existing = nil
		end

		local scriptObject = existing or Instance.new(info.className)
		scriptObject.Name = name
		setSource(scriptObject, info.source)
		if existing then
			updated += 1
		else
			scriptObject.Parent = container
			created += 1
		end
		table.insert(inserted, scriptObject)
	end

	-- Build the map right away so it shows in Studio's edit view (not only when you press Play).
	-- PlayCrafter games put map building in a ModuleScript called WorldBuilder with a Build(parent) function.
	local worldNote = nil
	for _, scriptObject in inserted do
		if scriptObject:IsA("ModuleScript") and scriptObject.Name == "WorldBuilder" then
			local fresh = scriptObject:Clone() -- a fresh copy so we never get an old cached version
			local ok, err = pcall(function()
				local builder = require(fresh)
				local build = type(builder) == "table" and builder.Build or builder
				if type(build) ~= "function" then
					error("WorldBuilder has no Build function")
				end
				build(workspace)
			end)
			fresh:Destroy()
			worldNote = ok and "World built: you can see it in the editor now."
				or ("Couldn't build the world in the editor (it will still build when you press Play): " .. tostring(err))
			break
		end
	end

	if recording then
		ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Commit)
	end
	if not keepSelection then
		Selection:Set(inserted)
	end
	return created, updated, skipped, worldNote
end

local function importMessage(created, updated, skipped, worldNote)
	local message = string.format("%d new script%s, %d updated.", created, created == 1 and "" or "s", updated)
	if worldNote then
		message ..= "\n" .. worldNote
	end
	if #skipped > 0 then
		message ..= "\nSkipped (unknown location): " .. table.concat(skipped, ", ")
	end
	return message
end

---------------------------------------------------------------------------
-- Buttons
---------------------------------------------------------------------------

local busy = false

local function refreshConnectedState(email)
	local connected = getToken() ~= nil
	codeLabel.Visible = not connected
	codeBox.Visible = not connected
	connectButton.Visible = not connected
	importButton.Visible = connected
	autoButton.Visible = connected
	disconnectButton.Visible = connected
	if connected then
		local how = plugin:GetSetting("AutoImport") ~= false
			and "New builds import automatically while this panel is open."
			or "Build on the website, then click Import."
		help.Text = (email and ("Connected as " .. email .. ". ") or "Connected. ") .. how
	else
		help.Text = "Build a game on the PlayCrafter website, then click Import to put every script into this place."
	end
end

connectButton.MouseButton1Click:Connect(function()
	if busy then return end
	local token = (codeBox.Text:gsub("%s", ""))
	if token == "" then
		setStatus("Paste your connect code first.", true)
		return
	end
	busy = true
	setStatus("Connecting...")
	local data, err = fetchLatest(token)
	busy = false
	if not data then
		setStatus(err, true)
		return
	end
	plugin:SetSetting("ConnectCode", token)
	-- Auto-import starts from builds made after connecting (older ones: use the Import button)
	plugin:SetSetting("LastImportedBuild", data.build and data.build.id or 0)
	plugin:SetSetting("AutoBaseline", true)
	codeBox.Text = ""
	refreshConnectedState(data.email)
	setStatus(data.build and "Connected! Click Import for your latest build. New builds will import by themselves."
		or "Connected! Build a game on the website and it will appear here by itself.")
end)

importButton.MouseButton1Click:Connect(function()
	if busy then return end
	local token = getToken()
	if not token then return end
	busy = true
	setStatus("Downloading your latest build...")
	local data, err = fetchLatest(token)
	if not data then
		busy = false
		setStatus(err, true)
		return
	end
	if not data.build or #data.build.scripts == 0 then
		busy = false
		setStatus("No build yet. Describe a game on the website first.", true)
		return
	end

	local created, updated, skipped, worldNote = importScripts(data.build.scripts)
	busy = false
	plugin:SetSetting("LastImportedBuild", data.build.id)

	local message = "Done! " .. importMessage(created, updated, skipped, worldNote)
	message ..= "\nCheck the website for any setup steps, then press Play. Ctrl+Z undoes the import."
	setStatus(message, #skipped > 0)
end)

local function refreshAutoButton()
	local on = plugin:GetSetting("AutoImport") ~= false
	autoButton.Text = on and "Auto-import: ON" or "Auto-import: OFF"
end
autoButton.MouseButton1Click:Connect(function()
	plugin:SetSetting("AutoImport", plugin:GetSetting("AutoImport") == false)
	refreshAutoButton()
	refreshConnectedState()
	setStatus(plugin:GetSetting("AutoImport") ~= false
		and "Auto-import is on: new builds go into this place by themselves while this panel is open."
		or "Auto-import is off: click Import when you want a build.")
end)
refreshAutoButton()

-- Auto-import: while the panel is open and you're editing (not playtesting), check for new builds
-- and import them in order (Big game mode builds arrive as several steps).
local lastError = nil
task.spawn(function()
	while true do
		task.wait(POLL_SECONDS)
		local token = getToken()
		if token and widget.Enabled and not busy and plugin:GetSetting("AutoImport") ~= false
			and RunService:IsEdit() and not RunService:IsRunning() then
			local after = plugin:GetSetting("LastImportedBuild") or 0
			local baselined = plugin:GetSetting("AutoBaseline") == true
			-- First run after updating the plugin: start from your newest build instead of re-importing old ones
			local path = baselined and ("/api/plugin/since?after=" .. tostring(after)) or "/api/plugin/since"
			local data, err = fetchJSON(token, path)
			if data and not baselined then
				plugin:SetSetting("LastImportedBuild", data.latestId or 0)
				plugin:SetSetting("AutoBaseline", true)
				data.builds = {}
			end
			if not data then
				if err ~= lastError then setStatus(err, true) end
				lastError = err
				task.wait(20) -- back off a little after an error
			else
				lastError = nil
				for _, build in data.builds or {} do
					busy = true
					local created, updated, skipped, worldNote = importScripts(build.scripts or {}, true)
					busy = false
					plugin:SetSetting("LastImportedBuild", build.id)
					setStatus("✓ New build imported automatically: " .. importMessage(created, updated, skipped, worldNote)
						.. "\nCheck the website for any setup steps, then press Play. Ctrl+Z undoes it.", #skipped > 0)
				end
			end
		end
	end
end)

disconnectButton.MouseButton1Click:Connect(function()
	plugin:SetSetting("ConnectCode", nil)
	refreshConnectedState()
	setStatus("Disconnected.")
end)

toggleButton.Click:Connect(function()
	widget.Enabled = not widget.Enabled
end)
widget:GetPropertyChangedSignal("Enabled"):Connect(function()
	toggleButton:SetActive(widget.Enabled)
end)

refreshConnectedState()
