--!nonstrict
--[[
	AP1X SENTINEL collector for Roblox experiences (ModuleScript in ServerScriptService).

	* Runs only on the server. Telemetry is batched and sent with HttpService:RequestAsync.
	* Command delivery uses outbound polling (Roblox servers cannot accept inbound connections).
	* Presence and movement are observed automatically. Combat, aim, trades and item lifecycle must be
	  reported by the experience's own server-authoritative code through the adapter API below;
	  client-originated claims must be validated by the game before being reported.
	* Moderation: ban/unban via Players:BanAsync / Players:UnbanAsync, kick via Player:Kick.
	  Inventory freeze and trade quarantine are available only when the game registers an adapter.

	Usage (server Script):
		local Sentinel = require(game.ServerScriptService.AP1XSentinel)
		local sentinel = Sentinel.new(require(game.ServerStorage.AP1XSentinelConfig))
		sentinel:start()
]]

local VERSION = "1.0.0"
local SCHEMA_VERSION = 1

export type Config = {
	ApiBaseUrl: string,
	CollectorKey: any, -- string, or a Secret from HttpService:GetSecret (preferred)
	FlushIntervalSeconds: number?,
	MaxBatchEvents: number?,
	MaxQueuedEvents: number?,
	MovementSampleHz: number?,
	CommandPollSeconds: number?,
	HeartbeatSeconds: number?,
	MaxRequestsPerMinute: number?,
	Debug: boolean?,
}

type Event = { [string]: any }

export type InventoryAdapter = {
	freeze: (player: Player, seconds: number, reason: string) -> (boolean, string?),
}

export type TradeQuarantineAdapter = {
	quarantine: (userIds: { number }, seconds: number, reason: string) -> (boolean, string?),
}

local Sentinel = {}
Sentinel.__index = Sentinel
Sentinel.VERSION = VERSION

local function defaultServices()
	return {
		HttpService = game:GetService("HttpService"),
		Players = game:GetService("Players"),
		RunService = game:GetService("RunService"),
		game = game,
		Enum = Enum,
		clock = os.clock,
		now = function(): number
			return DateTime.now().UnixTimestampMillis / 1000
		end,
		isoNow = function(): string
			return DateTime.now():ToIsoDate()
		end,
		isoAt = function(unixSeconds: number): string
			return DateTime.fromUnixTimestampMillis(math.floor(unixSeconds * 1000)):ToIsoDate()
		end,
		spawn = task.spawn,
		wait = task.wait,
		random = Random.new(),
		log = function(level: string, message: string)
			if level == "warn" then
				warn("[AP1XSentinel] " .. message)
			else
				print("[AP1XSentinel] " .. message)
			end
		end,
	}
end

local function validateConfig(config: Config)
	assert(type(config) == "table", "AP1XSentinel: configuration table required")
	assert(type(config.ApiBaseUrl) == "string" and string.match(config.ApiBaseUrl, "^https?://") ~= nil,
		"AP1XSentinel: ApiBaseUrl must be an http(s) URL ending in /api/v1")
	local key = config.CollectorKey
	assert(
		typeof(key) == "Secret" or (type(key) == "string" and string.match(key, "^ap1x_[a-z0-9]+_.+") ~= nil),
		"AP1XSentinel: CollectorKey missing or malformed (load it from a server-only secret)"
	)
	for _, field in { "FlushIntervalSeconds", "MaxBatchEvents", "MaxQueuedEvents", "MovementSampleHz", "CommandPollSeconds", "HeartbeatSeconds", "MaxRequestsPerMinute" } do
		local value = (config :: any)[field]
		assert(value == nil or (type(value) == "number" and value > 0), "AP1XSentinel: " .. field .. " must be a positive number")
	end
end

function Sentinel.new(config: Config, services: any?)
	validateConfig(config)
	local svc = services or defaultServices()
	local self = setmetatable({}, Sentinel)
	self.config = config
	self.services = svc
	self.apiBase = string.gsub(config.ApiBaseUrl, "/+$", "")
	-- Secrets can only be combined via AddPrefix and are accepted directly in request headers.
	self.authorization = if typeof(config.CollectorKey) == "Secret"
		then config.CollectorKey:AddPrefix("Bearer ")
		else "Bearer " .. config.CollectorKey
	self.flushInterval = config.FlushIntervalSeconds or 1
	self.maxBatch = math.min(config.MaxBatchEvents or 200, 500)
	self.maxQueued = config.MaxQueuedEvents or 5000
	self.movementInterval = 1 / (config.MovementSampleHz or 4)
	self.pollInterval = config.CommandPollSeconds or 3
	self.heartbeatInterval = config.HeartbeatSeconds or 30
	self.maxRequestsPerMinute = math.min(config.MaxRequestsPerMinute or 200, 450)
	self.queue = {} :: { Event }
	self.dropped = 0
	self.sequence = 0
	self.instanceId = svc.HttpService:GenerateGUID(false):lower()
	self.inFlight = nil :: { batch: { [string]: any }, attempts: number, nextAttemptAt: number }?
	self.requestTimes = {} :: { number }
	self.executedCommands = {} :: { [string]: string }
	self.lastShotAt = {} :: { [string]: number }
	self.inventoryAdapter = nil :: InventoryAdapter?
	self.tradeAdapter = nil :: TradeQuarantineAdapter?
	self.running = false
	self.connections = {}
	return self
end

-- ------------------------------------------------------------------ helpers

function Sentinel:_uuid(): string
	return self.services.HttpService:GenerateGUID(false):lower()
end

function Sentinel:_log(level: string, message: string)
	if level ~= "debug" or self.config.Debug then
		self.services.log(level, message)
	end
end

function Sentinel:enqueue(eventType: string, playerId: string?, data: { [string]: any }, occurredAt: string?)
	if #self.queue >= self.maxQueued then
		table.remove(self.queue, 1)
		self.dropped += 1
	end
	table.insert(self.queue, {
		event_id = self:_uuid(),
		event_type = eventType,
		occurred_at = occurredAt or self.services.isoNow(),
		player_id = playerId,
		data = data,
	})
end

function Sentinel:_allowRequest(): boolean
	local now = self.services.clock()
	local recent = {}
	for _, t in self.requestTimes do
		if now - t < 60 then
			table.insert(recent, t)
		end
	end
	self.requestTimes = recent
	if #recent >= self.maxRequestsPerMinute then
		return false
	end
	table.insert(self.requestTimes, now)
	return true
end

function Sentinel:_request(method: string, path: string, body: any?): (boolean, number, any)
	if not self:_allowRequest() then
		return false, 429, "local request budget exhausted"
	end
	local http = self.services.HttpService
	local options = {
		Url = self.apiBase .. path,
		Method = method,
		Headers = {
			["Authorization"] = self.authorization,
			["Content-Type"] = "application/json",
		},
		Body = if body ~= nil then http:JSONEncode(body) else nil,
	}
	local ok, response = pcall(function()
		return http:RequestAsync(options)
	end)
	if not ok then
		return false, 0, tostring(response)
	end
	local decoded = nil
	if response.Body and #response.Body > 0 then
		local parsed, value = pcall(function()
			return http:JSONDecode(response.Body)
		end)
		decoded = if parsed then value else response.Body
	end
	return response.Success, response.StatusCode, decoded
end

-- ------------------------------------------------------------------ telemetry transport

function Sentinel:flush()
	local now = self.services.clock()
	if self.inFlight == nil then
		if #self.queue == 0 then
			return
		end
		local events = {}
		for i = 1, math.min(self.maxBatch, #self.queue) do
			events[i] = self.queue[i]
		end
		for _ = 1, #events do
			table.remove(self.queue, 1)
		end
		self.sequence += 1
		self.inFlight = {
			batch = {
				batch_id = self:_uuid(),
				schema_version = SCHEMA_VERSION,
				collector = { platform = "roblox", version = VERSION, instance_id = self.instanceId, sequence_number = self.sequence },
				sent_at = self.services.isoNow(),
				events = events,
			},
			attempts = 0,
			nextAttemptAt = now,
		}
	end
	local pending = self.inFlight :: any
	if now < pending.nextAttemptAt then
		return
	end
	local ok, status, body = self:_request("POST", "/collector/telemetry/batches", pending.batch)
	if ok then
		self.inFlight = nil
		self:_log("debug", string.format("batch accepted (%d events)", #pending.batch.events))
		return
	end
	if status == 0 or status == 429 or status >= 500 then
		-- Transient: retry the same batch (same batch_id/sequence) with exponential backoff and jitter.
		pending.attempts += 1
		local delay = math.min(60, 2 ^ pending.attempts) * (0.5 + self.services.random:NextNumber())
		pending.nextAttemptAt = now + delay
		self:_log("warn", string.format("telemetry send failed (status %d); retry in %.1fs", status, delay))
	else
		-- Permanent rejection (validation/auth): drop the batch and report why.
		self.inFlight = nil
		local code = if type(body) == "table" and body.error then body.error.code else tostring(status)
		self:_log("warn", "telemetry batch rejected: " .. tostring(code))
	end
end

function Sentinel:sendHeartbeat()
	local ok, status = self:_request("POST", "/collector/heartbeat", {
		collector_version = VERSION,
		instance_id = self.instanceId,
		online_players = #self.services.Players:GetPlayers(),
		queue_depth = #self.queue,
		dropped_events = self.dropped,
	})
	if not ok then
		self:_log("warn", "heartbeat failed with status " .. tostring(status))
	end
end

function Sentinel:capabilities(): { [string]: any }
	return {
		signals = {
			presence = true,
			movement = true,
			aim = { available = true, reason = "Only aim reported by the game's server-validated code." },
			combat_interval = true,
			economy_transfer = true,
			resource_lifecycle = true,
		},
		features = {
			inventory_freeze = self.inventoryAdapter ~= nil,
			trade_quarantine = self.tradeAdapter ~= nil,
		},
	}
end

function Sentinel:announceCapabilities()
	self:enqueue("collector.capabilities", nil, self:capabilities())
end

-- ------------------------------------------------------------------ adapter API for game code

local function userId(player: Player | number): string
	return tostring(if type(player) == "number" then player else (player :: Player).UserId)
end

function Sentinel:reportAim(player: Player, yawDeg: number, pitchDeg: number, sampleIntervalMs: number)
	self:enqueue("aim.sample", userId(player), { yaw_deg = yawDeg, pitch_deg = math.clamp(pitchDeg, -90, 90), sample_interval_ms = sampleIntervalMs })
end

function Sentinel:reportCombat(player: Player, actionType: string, weaponId: string?)
	local key = userId(player) .. "|" .. (weaponId or "")
	local now = self.services.clock()
	local last = self.lastShotAt[key]
	self.lastShotAt[key] = now
	self:enqueue("combat.action", userId(player), {
		action_type = actionType,
		weapon_id = weaponId,
		interval_ms = if last then math.floor((now - last) * 1000 * 1000 + 0.5) / 1000 else nil,
	})
end

function Sentinel:reportTrade(from: Player | number, to: Player | number, itemType: string, quantity: number, options: { [string]: any }?)
	local opts = options or {}
	self:enqueue("economy.transfer", nil, {
		from_player_id = userId(from),
		to_player_id = userId(to),
		item_type = itemType,
		quantity = tostring(quantity),
		item_instance_id = opts.itemInstanceId,
		lineage_id = opts.lineageId,
		estimated_value = if opts.estimatedValue then tostring(opts.estimatedValue) else nil,
		transfer_context = opts.context or "trade",
	})
end

function Sentinel:reportResource(player: Player | number | nil, resourceType: string, quantity: number, originType: string, options: { [string]: any }?)
	local opts = options or {}
	self:enqueue("economy.resource", if player ~= nil then userId(player :: any) else nil, {
		resource_type = resourceType,
		quantity = tostring(quantity),
		origin_type = originType,
		item_instance_id = opts.itemInstanceId,
		lineage_id = opts.lineageId,
	})
end

function Sentinel:registerInventoryAdapter(adapter: InventoryAdapter)
	assert(type(adapter.freeze) == "function", "inventory adapter must implement freeze(player, seconds, reason)")
	self.inventoryAdapter = adapter
	self:announceCapabilities()
end

function Sentinel:registerTradeQuarantineAdapter(adapter: TradeQuarantineAdapter)
	assert(type(adapter.quarantine) == "function", "trade adapter must implement quarantine(userIds, seconds, reason)")
	self.tradeAdapter = adapter
	self:announceCapabilities()
end

-- ------------------------------------------------------------------ automatic observation

function Sentinel:samplePlayer(player: Player)
	local character = player.Character
	if not character then
		return
	end
	local root = character:FindFirstChild("HumanoidRootPart") :: BasePart?
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if not root or not humanoid then
		return
	end
	local RobloxEnum = self.services.Enum
	local state: string? = nil
	local hstate = humanoid:GetState()
	if humanoid.Sit or hstate == RobloxEnum.HumanoidStateType.Seated then
		state = "seated"
	elseif hstate == RobloxEnum.HumanoidStateType.Swimming then
		state = "swimming"
	elseif hstate == RobloxEnum.HumanoidStateType.Climbing then
		state = "climbing"
	elseif hstate == RobloxEnum.HumanoidStateType.Ragdoll or hstate == RobloxEnum.HumanoidStateType.FallingDown or hstate == RobloxEnum.HumanoidStateType.Physics then
		state = "ragdoll"
	elseif character:GetAttribute("AP1XTeleportAuthorized") then
		state = "teleport_authorized"
	end
	local position = root.Position
	self:enqueue("movement.sample", userId(player), {
		x = position.X,
		y = position.Y,
		z = position.Z,
		grounded = humanoid.FloorMaterial ~= RobloxEnum.Material.Air,
		vertical_velocity = root.AssemblyLinearVelocity.Y,
		movement_state = state,
		world_id = tostring(self.services.game.PlaceId),
	})
end

-- ------------------------------------------------------------------ commands

local KNOWN_COMMANDS = { ban = true, unban = true, kick = true, freeze_inventory = true, quarantine_trade_chain = true }

function Sentinel:_validateCommand(command: any): (boolean, string?)
	if type(command) ~= "table" or type(command.command_id) ~= "string" then
		return false, "malformed command"
	end
	if not KNOWN_COMMANDS[command.command_type] then
		return false, "COMMAND_UNSUPPORTED"
	end
	if type(command.parameters) ~= "table" or type(command.parameters.reason) ~= "string" then
		return false, "INVALID_PARAMETERS"
	end
	if command.command_type ~= "quarantine_trade_chain" then
		local target = command.target and command.target.player_id
		if type(target) ~= "string" or tonumber(target) == nil then
			return false, "INVALID_TARGET"
		end
	end
	return true, nil
end

function Sentinel:executeCommand(command: any): (string, string, string?)
	local players = self.services.Players
	local params = command.parameters
	local target = command.target and tonumber(command.target.player_id)
	local kind = command.command_type
	if kind == "kick" then
		local player = players:GetPlayerByUserId(target)
		if not player then
			return "failed", "Player is not in this server.", "PLAYER_NOT_ONLINE"
		end
		player:Kick(params.reason)
		return "succeeded", "Player kicked from this server.", nil
	elseif kind == "ban" then
		local duration = if params.permanent then -1 else params.duration_seconds
		local ok, err = pcall(function()
			players:BanAsync({
				UserIds = { target },
				ApplyToUniverse = true,
				Duration = duration,
				DisplayReason = params.reason,
				PrivateReason = "AP1X SENTINEL command " .. command.command_id,
				ExcludeAltAccounts = false,
			})
		end)
		if not ok then
			return "failed", tostring(err), "PLATFORM_ACTION_FAILED"
		end
		return "succeeded", "Players:BanAsync applied to the universe.", nil
	elseif kind == "unban" then
		local ok, err = pcall(function()
			players:UnbanAsync({ UserIds = { target }, ApplyToUniverse = true })
		end)
		if not ok then
			return "failed", tostring(err), "PLATFORM_ACTION_FAILED"
		end
		return "succeeded", "Players:UnbanAsync applied to the universe.", nil
	elseif kind == "freeze_inventory" then
		if not self.inventoryAdapter then
			return "failed", "No inventory adapter is registered by this experience.", "COMMAND_UNSUPPORTED"
		end
		local player = players:GetPlayerByUserId(target)
		if not player then
			return "failed", "Player is not in this server.", "PLAYER_NOT_ONLINE"
		end
		local ok, message = (self.inventoryAdapter :: InventoryAdapter).freeze(player, params.duration_seconds, params.reason)
		return if ok then "succeeded" else "failed", message or "inventory adapter result", if ok then nil else "PLATFORM_ACTION_FAILED"
	elseif kind == "quarantine_trade_chain" then
		if not self.tradeAdapter then
			return "failed", "No trade quarantine adapter is registered by this experience.", "COMMAND_UNSUPPORTED"
		end
		local ids = {}
		for _, id in params.player_ids or {} do
			local numeric = tonumber(id)
			if numeric then
				table.insert(ids, numeric)
			end
		end
		local ok, message = (self.tradeAdapter :: TradeQuarantineAdapter).quarantine(ids, params.duration_seconds, params.reason)
		return if ok then "succeeded" else "failed", message or "trade adapter result", if ok then nil else "PLATFORM_ACTION_FAILED"
	end
	return "failed", "Unsupported command.", "COMMAND_UNSUPPORTED"
end

function Sentinel:pollCommands()
	local ok, status, body = self:_request("GET", "/collector/commands", nil)
	if not ok then
		if status ~= 429 then
			self:_log("warn", "command poll failed with status " .. tostring(status))
		end
		return
	end
	for _, command in (body and body.commands) or {} do
		local commandId = command.command_id
		local previous = self.executedCommands[commandId]
		if previous then
			-- Already executed (redelivery): report the stored outcome again, never re-execute.
			self:_request("POST", "/collector/commands/" .. commandId .. "/result", {
				status = previous, executed_at = self.services.isoNow(), result = { platform_action_id = nil, message = "Duplicate delivery; already executed." },
			})
			continue
		end
		local valid, reason = self:_validateCommand(command)
		local ackOk = self:_request("POST", "/collector/commands/" .. tostring(commandId) .. "/ack", {})
		if not ackOk then
			continue
		end
		local resultStatus, message, errorCode
		if not valid then
			resultStatus, message, errorCode = "failed", "Command rejected by collector validation.", reason
		else
			resultStatus, message, errorCode = self:executeCommand(command)
		end
		self.executedCommands[commandId] = resultStatus
		self:_request("POST", "/collector/commands/" .. commandId .. "/result", {
			status = resultStatus,
			executed_at = self.services.isoNow(),
			result = { platform_action_id = nil, message = message },
			error_code = errorCode,
			error_message = if errorCode then message else nil,
		})
	end
end

-- ------------------------------------------------------------------ lifecycle

function Sentinel:start()
	assert(self.services.RunService:IsServer(), "AP1XSentinel must run on the server")
	if self.running then
		return
	end
	self.running = true
	local players = self.services.Players
	table.insert(self.connections, players.PlayerAdded:Connect(function(player: Player)
		self:enqueue("player.join", userId(player), { display_name = player.Name })
	end))
	table.insert(self.connections, players.PlayerRemoving:Connect(function(player: Player)
		self:enqueue("player.leave", userId(player), { reason = "removed" })
	end))
	for _, player in players:GetPlayers() do
		self:enqueue("player.join", userId(player), { display_name = player.Name })
	end
	self:announceCapabilities()
	local svc = self.services
	svc.spawn(function()
		while self.running do
			for _, player in svc.Players:GetPlayers() do
				self:samplePlayer(player)
			end
			svc.wait(self.movementInterval)
		end
	end)
	svc.spawn(function()
		while self.running do
			self:flush()
			svc.wait(self.flushInterval)
		end
	end)
	svc.spawn(function()
		while self.running do
			self:pollCommands()
			svc.wait(self.pollInterval)
		end
	end)
	svc.spawn(function()
		while self.running do
			self:sendHeartbeat()
			svc.wait(self.heartbeatInterval)
		end
	end)
	self.services.game:BindToClose(function()
		self:stop()
	end)
	self:_log("info", "collector " .. VERSION .. " started")
end

function Sentinel:stop()
	if not self.running then
		return
	end
	self.running = false
	for _, connection in self.connections do
		connection:Disconnect()
	end
	self.connections = {}
	-- Best-effort final flush within BindToClose's time budget.
	for _ = 1, 3 do
		if #self.queue == 0 and self.inFlight == nil then
			break
		end
		if self.inFlight then
			(self.inFlight :: any).nextAttemptAt = 0
		end
		self:flush()
	end
end

return Sentinel
