--!strict
-- BloxTrack: analytics for Roblox games. https://bloxtrack-app.vercel.app/docs
--
-- A server ModuleScript. Put it in ServerScriptService, name it "BloxTrack", and start it once from a server Script:
--
--     local BloxTrack = require(game:GetService("ServerScriptService").BloxTrack)
--     BloxTrack.Start({ key = "btk_in_..." })   -- your project's ingest key (keep it on the server)
--
-- Then, wherever something happens:
--
--     BloxTrack.Track(player, "purchase", "sword", 25)   -- name, key (what it was about), value (an amount)
--
-- It tracks session_start (with device, country, locale, how they joined) and session_end (seconds played) for you,
-- sends events in batches every 15 seconds, keeps them through short outages, and sends the rest on shutdown.
-- Turn on Game Settings > Security > Allow HTTP Requests, or nothing can be sent.
--
-- Optional client part: BloxTrackClient (a ModuleScript in ReplicatedStorage) reports each player's device
-- (phone, tablet, desktop, console) and lets LocalScripts send the events you allow in `clientEvents`.

local HttpService = game:GetService("HttpService")
local LocalizationService = game:GetService("LocalizationService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")

local BloxTrack = {}
BloxTrack.VERSION = "1.0.0"

local DEFAULT_URL = "https://bloxtrack-api.stockideashq.workers.dev/v1/events"
local FLUSH_EVERY = 15 -- seconds between sends
local BATCH_SIZE = 200 -- events per request (the API takes up to 500)
local MAX_QUEUE = 5000 -- while the API can't be reached, the oldest events beyond this are dropped
local DEVICE_WAIT = 10 -- seconds session_start waits for the client to report its device
local CLIENT_LIMIT = 60 -- client events per player per minute
local REMOTE_NAME = "BloxTrackRemote"
local NAME_PATTERN = "^[a-z][a-z0-9_]*$"
local DEVICES = { phone = true, tablet = true, desktop = true, console = true }

export type Options = {
	key: string, -- the project's ingest key (btk_in_...)
	testPlaceIds: { number }?, -- places whose events count as "test" (Studio is always "studio", the rest "live")
	-- Whether this is the player's first time in the game (they have no save). May yield (wait for your save to
	-- load). Without it, the first session BloxTrack sees for a player counts as their first.
	isNewPlayer: ((player: Player) -> boolean)?,
	-- Extra props for session_start (level, coins, ...). May yield.
	sessionProps: ((player: Player) -> { [string]: any })?,
	clientEvents: { string }?, -- event names LocalScripts may send through BloxTrackClient
	autoSessions: boolean?, -- send session_start / session_end (default true)
	debug: boolean?, -- print every send (Studio prints problems either way)
	url: string?, -- the events endpoint (default: BloxTrack's)
}

type Session = { id: string, joined: number, device: string?, ended: boolean }

local options: Options? = nil
local env = "live"
local serverId = if game.JobId ~= "" then game.JobId else HttpService:GenerateGUID(false)
local queue: { any } = {}
local sending = false
local sessions: { [Player]: Session } = {}
local stepLists: { [string]: { string } } = {}
local stepIndex: { [string]: { [string]: number } } = {}
local stepsSent = true -- nothing to send until DefineSteps
local clientAllowed: { [string]: boolean } = {}
local clientCounts: { [Player]: { minute: number, count: number } } = {}
local warned: { [string]: boolean } = {}

local function warnOnce(id: string, message: string)
	if not warned[id] then
		warned[id] = true
		warn("[BloxTrack] " .. message)
	end
end

local function now(): number
	return DateTime.now().UnixTimestampMillis
end

local function session(player: Player): Session
	local s = sessions[player]
	if not s then
		s = { id = HttpService:GenerateGUID(false), joined = os.clock(), ended = false }
		sessions[player] = s
	end
	return s
end

local function enqueue(player: Player, name: string, key: (string | number)?, value: number?, props: { [string]: any }?, ts: number?)
	if not options then
		warnOnce("notStarted", "Track called before BloxTrack.Start: event dropped (" .. tostring(name) .. ")")
		return
	end
	if typeof(player) ~= "Instance" or not player:IsA("Player") then
		warnOnce("player:" .. tostring(name), "Track's first argument must be a Player (event " .. tostring(name) .. ")")
		return
	end
	if typeof(name) ~= "string" or #name > 40 or not string.match(name, NAME_PATTERN) then
		warnOnce("name:" .. tostring(name), "bad event name " .. tostring(name) .. ": use snake_case (a-z, 0-9, _), up to 40 characters")
		return
	end
	if player.UserId <= 0 then
		return -- Studio's test players in a local server have negative ids
	end
	table.insert(queue, {
		id = HttpService:GenerateGUID(false),
		name = name,
		key = if key ~= nil then tostring(key) else nil,
		value = if typeof(value) == "number" and value == value then value else nil,
		user_id = player.UserId,
		session_id = session(player).id,
		ts = ts or now(),
		props = props,
	})
	if #queue > MAX_QUEUE then
		table.remove(queue, 1)
	end
	if #queue >= BATCH_SIZE then
		task.defer(BloxTrack.Flush)
	end
end

--- Records that `player` did something.
--- name: what happened, snake_case ("purchase", "level_up", "tutorial_step").
--- key: what it was about, a string (the item, level, step, area). Optional.
--- value: an amount (coins, Robux, seconds). Optional.
--- props: anything else, a small table of strings, numbers and booleans. Optional.
function BloxTrack.Track(player: Player, name: string, key: (string | number)?, value: number?, props: { [string]: any }?)
	enqueue(player, name, key, value, props)
end

--- Declares a list of steps (a tutorial, an onboarding, a quest chain) sent as event `name`, in order. The dashboard
--- then shows every step, even ones nobody has reached yet. Call once at startup, before players reach any step.
function BloxTrack.DefineSteps(name: string, list: { string })
	stepLists[name] = list
	local index = {}
	for i, step in list do
		index[step] = i
	end
	stepIndex[name] = index
	stepsSent = false
end

--- Records that `player` reached `step` of the step list `name` (see DefineSteps). value: optional, e.g. seconds.
function BloxTrack.Step(player: Player, name: string, step: string, value: number?)
	local index = stepIndex[name] and stepIndex[name][step]
	if not index then
		warnOnce("step:" .. name .. ":" .. step, "step " .. step .. " isn't in DefineSteps(\"" .. name .. "\", ...): sent without its number")
	end
	BloxTrack.Track(player, name, step, value, if index then { index = index } else nil)
end

--- Sends everything queued now. Called for you every 15 seconds and on shutdown.
function BloxTrack.Flush()
	local opts = options
	if sending or not opts then
		return
	end
	sending = true
	while #queue > 0 or not stepsSent do
		local batch = table.move(queue, 1, math.min(BATCH_SIZE, #queue), 1, {})
		local body = HttpService:JSONEncode({
			env = env,
			version = game.PlaceVersion,
			server_id = serverId,
			events = batch,
			steps = if stepsSent then nil else stepLists,
		})
		local ok, response = pcall(HttpService.RequestAsync, HttpService, {
			Url = opts.url or DEFAULT_URL,
			Method = "POST",
			Headers = { ["Content-Type"] = "application/json", Authorization = "Bearer " .. opts.key },
			Body = body,
		})
		if ok and response.Success then
			queue = table.move(queue, #batch + 1, #queue, 1, {}) -- drop the sent ones from the front
			stepsSent = true
			local okDecode, decoded = pcall(HttpService.JSONDecode, HttpService, response.Body)
			if opts.debug then
				print("[BloxTrack] sent " .. #batch .. " events: " .. response.Body)
			end
			if okDecode and typeof(decoded) == "table" and decoded.errors then
				warnOnce("rejected", "some events were rejected: " .. HttpService:JSONEncode(decoded.errors))
			end
		elseif ok and response.StatusCode >= 400 and response.StatusCode < 500 and response.StatusCode ~= 429 then
			-- The API said no (a bad key, a bad batch): resending won't help, so these are dropped.
			queue = table.move(queue, #batch + 1, #queue, 1, {})
			stepsSent = true
			warnOnce("http" .. response.StatusCode, "the API refused " .. #batch .. " events: " .. response.StatusCode .. " " .. response.Body)
		else
			local reason = if ok then response.StatusCode .. " " .. response.Body else tostring(response)
			if string.find(reason, "Http requests are not enabled", 1, true) then
				warnOnce("http", "turn on Game Settings > Security > Allow HTTP Requests, or no events can be sent")
			elseif opts.debug or RunService:IsStudio() then
				warn("[BloxTrack] couldn't send " .. #batch .. " events (kept for the next try): " .. reason)
			end
			break
		end
	end
	sending = false
end

-- How the player got here: a friend's invite link, following someone, from another game, or straight in.
local function joinSource(player: Player): (string, number?)
	local ok, data = pcall(player.GetJoinData, player)
	local join = if ok and typeof(data) == "table" then data else {}
	if (join.ReferredByPlayerId or 0) > 0 then
		return "friend_invite", join.ReferredByPlayerId
	elseif player.FollowUserId ~= 0 then
		return "follow", nil
	elseif (join.SourceGameId or 0) ~= 0 and join.SourceGameId ~= game.GameId then
		return "other_game", nil
	end
	return "direct", nil
end

local function startSession(player: Player)
	local opts = options :: Options
	local s = session(player)
	local joinedAt = now()
	task.spawn(function()
		local waited = 0
		while not s.device and waited < DEVICE_WAIT and player.Parent do
			waited += task.wait(0.5)
		end
		local okCountry, country = pcall(LocalizationService.GetCountryRegionForPlayerAsync, LocalizationService, player)
		local source, referrer = joinSource(player)
		local props: { [string]: any } = {
			device = s.device,
			country = if okCountry then country else nil,
			locale = player.LocaleId,
			join_source = source,
			referred_by = referrer,
			account_age_days = player.AccountAge,
		}
		if opts.isNewPlayer then
			local ok, isNew = pcall(opts.isNewPlayer, player)
			if ok and typeof(isNew) == "boolean" then
				props.new_player = isNew
			end
		end
		if opts.sessionProps then
			local ok, extra = pcall(opts.sessionProps, player)
			if ok and typeof(extra) == "table" then
				for k, v in extra do
					props[k] = v
				end
			end
		end
		-- At the time they joined, not when the props were ready (so it comes before their other events).
		enqueue(player, "session_start", nil, nil, props, joinedAt)
	end)
end

local function endSession(player: Player)
	local s = sessions[player]
	if not s or s.ended then
		return
	end
	s.ended = true
	if options and options.autoSessions ~= false then
		BloxTrack.Track(player, "session_end", nil, math.floor(os.clock() - s.joined), { device = s.device })
	end
	task.delay(5, function()
		sessions[player] = nil -- late events from other scripts can still use the session for a moment
		clientCounts[player] = nil
	end)
end

-- Client → server: { "device", "phone" } once at start, or { "event", name, key, value, props } for clientEvents.
local function onClient(player: Player, kind: any, a: any, b: any, c: any, d: any)
	if kind == "device" then
		if typeof(a) == "string" and DEVICES[a] then
			session(player).device = a
		end
		return
	end
	if kind ~= "event" or typeof(a) ~= "string" or not clientAllowed[a] then
		return
	end
	local minute = math.floor(os.clock() / 60)
	local count = clientCounts[player]
	if not count or count.minute ~= minute then
		count = { minute = minute, count = 0 }
		clientCounts[player] = count
	end
	count.count += 1
	if count.count > CLIENT_LIMIT then
		return
	end
	local key = if typeof(b) == "string" then string.sub(b, 1, 100) elseif typeof(b) == "number" then b else nil
	local value = if typeof(c) == "number" then c else nil
	local props = if typeof(d) == "table" then d else nil
	if props and #HttpService:JSONEncode(props) > 1000 then
		props = nil
	end
	BloxTrack.Track(player, a, key, value, props)
end

--- Starts BloxTrack. Call once, from a server Script, before tracking anything.
function BloxTrack.Start(opts: Options)
	assert(RunService:IsServer(), "BloxTrack.Start runs on the server (a Script), not in a LocalScript")
	if options then
		warnOnce("startedTwice", "BloxTrack.Start was called twice: the second call is ignored")
		return
	end
	if typeof(opts) ~= "table" or typeof(opts.key) ~= "string" or string.sub(opts.key, 1, 7) ~= "btk_in_" then
		warn("[BloxTrack] Start needs { key = \"btk_in_...\" }, your project's ingest key: nothing will be sent")
		return
	end
	options = opts
	env = "live"
	if RunService:IsStudio() then
		env = "studio"
	elseif opts.testPlaceIds and table.find(opts.testPlaceIds, game.PlaceId) then
		env = "test"
	end
	local okHttp, httpOn = pcall(function()
		return HttpService.HttpEnabled
	end)
	if okHttp and httpOn == false then
		warn("[BloxTrack] Allow HTTP Requests is off (Game Settings > Security): events will wait until it's on")
	end

	for _, name in opts.clientEvents or {} do
		clientAllowed[name] = true
	end
	local remote = ReplicatedStorage:FindFirstChild(REMOTE_NAME)
	if not remote then
		remote = Instance.new("RemoteEvent")
		remote.Name = REMOTE_NAME
		remote.Parent = ReplicatedStorage
	end
	(remote :: RemoteEvent).OnServerEvent:Connect(onClient)

	if opts.autoSessions ~= false then
		Players.PlayerAdded:Connect(startSession)
		for _, player in Players:GetPlayers() do
			startSession(player)
		end
	end
	Players.PlayerRemoving:Connect(endSession)

	task.spawn(function()
		while true do
			task.wait(FLUSH_EVERY)
			BloxTrack.Flush()
		end
	end)

	game:BindToClose(function()
		for _, player in Players:GetPlayers() do
			endSession(player)
		end
		local waited = 0
		while sending and waited < 5 do -- let a send in progress finish first
			waited += task.wait(0.1)
		end
		BloxTrack.Flush()
	end)

	if opts.debug or RunService:IsStudio() then
		print("[BloxTrack] started: env " .. env .. ", place version " .. game.PlaceVersion)
	end
end

return BloxTrack
