local _, GF = ...

GF.Search = GF.Search or {}
local Search = GF.Search
local NativeSearch = GF.NativeSearchGateway
local MemoryDiagnostics = GF.SearchMemoryDiagnostics

local function currentTime()
	if type(GetTime) ~= "function" then
		return nil
	end
	local ok, value = pcall(GetTime)
	return ok and tonumber(value) or nil
end

local function hasKeywordSearch()
	local hasKeyword = false
	if GF.FindGroupTab and GF.FindGroupTab.GetBrowseSearchState then
		hasKeyword = GF.FindGroupTab:GetBrowseSearchState()
	end
	return hasKeyword == true
end

local function readCurrentResultIDs()
	if not (NativeSearch and NativeSearch.ReadResults) then
		return 0, {}
	end
	return NativeSearch:ReadResults(hasKeywordSearch())
end

local function normalizeScope(selection, scope)
	if not scope then
		return nil
	end
	local categoryID = scope.categoryID or (selection and selection.categoryID)
	if not categoryID then
		return nil
	end
	local preferredFilters = scope.preferredFilters
		or (selection and selection.preferredFilters)
		or Enum.LFGListFilter.PvE
	local activityID = scope.activityID or (selection and selection.activityID)
	local activityIDsFilter = scope.activityIDsFilter
	local questID
	if selection and selection._gfQuestSearch == true then
		local rawQuestID = scope.questID or selection.questID
		questID = GF.QuestSearch and GF.QuestSearch.NormalizeQuestID
			and GF.QuestSearch:NormalizeQuestID(rawQuestID) or nil
	end
	if not activityIDsFilter and not scope.resultActivityIDsFilter
		and activityID and not scope.categoryBrowse
		and not (selection and selection.categoryBrowse)
	then
		activityIDsFilter = { activityID }
	end

	local baseFilters = scope.filters or (selection and selection.filters) or 0
	local filters = GF.Filter and GF.Filter:ResolveCategoryFilters(
		categoryID, baseFilters) or baseFilters
	if GF.Filter and GF.Filter.ResolvePreferredFilters then
		preferredFilters = GF.Filter:ResolvePreferredFilters(
			categoryID, preferredFilters)
	end

	return {
		categoryID = categoryID,
		filters = filters,
		preferredFilters = preferredFilters,
		activityIDsFilter = activityIDsFilter,
		resultActivityIDsFilter = scope.resultActivityIDsFilter,
		navKind = scope.navKind or (selection and selection.navKind),
		questID = questID,
	}
end

local function mergeIDsInto(target, seen, ids)
	if not target or not seen or not ids then
		return
	end
	for _, id in ipairs(ids) do
		if id and not seen[id] then
			seen[id] = true
			target[#target + 1] = id
		end
	end
end

local function mergeNormalizedScopes(scopes)
	local merged = {}
	local order = {}
	for _, scope in ipairs(scopes or {}) do
		if scope and scope.categoryID then
			local hasNativeIDs = scope.activityIDsFilter
				and #scope.activityIDsFilter > 0
			local hasResultIDs = scope.resultActivityIDsFilter
				and #scope.resultActivityIDsFilter > 0
			local exact = hasNativeIDs or hasResultIDs
			local key = table.concat({
				tostring(scope.categoryID),
				tostring(scope.preferredFilters or 0),
				tostring(scope.questID or ""),
				exact and "exact" or ("broad:" .. tostring(scope.filters or 0)),
			}, ":")
			local output = merged[key]
			if not output then
				output = {
					categoryID = scope.categoryID,
					filters = scope.filters or 0,
					preferredFilters = scope.preferredFilters,
					navKind = scope.navKind,
					questID = scope.questID,
					_exact = exact,
					_scopeCount = 0,
					_activityIDs = exact and {} or nil,
					_seenActivityIDs = exact and {} or nil,
					_needsResultFilter = hasResultIDs == true,
				}
				merged[key] = output
				order[#order + 1] = key
			end
			output._scopeCount = output._scopeCount + 1
			output._needsResultFilter = output._needsResultFilter
				or hasResultIDs == true
			if exact then
				mergeIDsInto(
					output._activityIDs,
					output._seenActivityIDs,
					scope.activityIDsFilter
				)
				mergeIDsInto(
					output._activityIDs,
					output._seenActivityIDs,
					scope.resultActivityIDsFilter
				)
			end
		end
	end

	local result = {}
	for _, key in ipairs(order) do
		local scope = merged[key]
		if scope._exact then
			if scope._scopeCount > 1 then
				-- Exact scopes from one user action can be represented as a single
				-- activity union. Category filters are redundant for that union and
				-- can wrongly exclude archived or mixed-difficulty activities.
				scope.filters = 0
			end
			if scope.categoryID == GF.CAT_CUSTOM then
				scope.resultActivityIDsFilter = scope._activityIDs
			else
				scope.activityIDsFilter = scope._activityIDs
				if scope._needsResultFilter then
					scope.resultActivityIDsFilter = scope._activityIDs
				end
			end
		end
		scope._exact = nil
		scope._scopeCount = nil
		scope._activityIDs = nil
		scope._seenActivityIDs = nil
		scope._needsResultFilter = nil
		result[#result + 1] = scope
	end
	return result
end

local function clearAggregate(owner)
	owner.aggregate = nil
	owner.aggregateResultIDs = nil
	owner.aggregateTotal = nil
	owner.aggregateInfoByID = nil
	owner.aggregateMemberCountsByID = nil
end

function Search:_SetSession(session)
	self.session = session
	self.context = session and session.context or nil
	self.pending = session and session.aggregation or nil
	self.inFlight = session and session.state == "searching" or false
end

function Search:_CompleteSession()
	local session = self.session
	if session then
		session.state = "complete"
		session.completedAt = currentTime()
		session.aggregation = nil
	end
	self.pending = nil
	self.inFlight = false
end

function Search:Reset()
	if MemoryDiagnostics and MemoryDiagnostics.AbortSearch then
		MemoryDiagnostics:AbortSearch("reset")
	end
	self:_SetSession(nil)
	clearAggregate(self)
end

function Search:GetRequestBarrierRemaining()
	local expiresAt = tonumber(self.abandonedUntil)
	if not expiresAt then
		self.barrier = nil
		return 0
	end
	local now = currentTime()
	if not now then
		return 0
	end
	local remaining = expiresAt - now
	if remaining <= 0 then
		self.abandonedUntil = nil
		self.abandonedContext = nil
		self.barrier = nil
		return 0
	end
	return remaining
end

function Search:GetCooldownRemaining()
	local startedAt = tonumber(self.lastNativeSearchAt)
	local now = currentTime()
	if not startedAt or not now then
		if not startedAt then
			self.cooldown = nil
		end
		return 0
	end
	local duration = GF.SEARCH_COOLDOWN or 3
	local remaining = duration - (now - startedAt)
	if remaining <= 0 then
		return 0
	end
	return remaining
end

function Search:_RecordNativeSearchStart()
	local startedAt = currentTime()
	if not startedAt then
		return
	end
	self.lastNativeSearchAt = startedAt
	self.cooldown = {
		startedAt = startedAt,
		duration = GF.SEARCH_COOLDOWN or 3,
	}
	if self.session then
		self.session.startedAt = startedAt
	end
end

function Search:AbandonActiveRequest()
	local session = self.session
	local wasInFlight = self.inFlight == true
		or (session and session.state == "searching")
	local now = currentTime()
	if wasInFlight and now then
		local expiresAt = now + (GF.SEARCH_TIMEOUT_SECONDS or 8)
		self.abandonedUntil = expiresAt
		self.abandonedContext = self.context
		self.barrier = {
			expiresAt = expiresAt,
			context = self.context,
			sessionID = session and session.id or nil,
		}
	end
	self:Reset()
	return wasInFlight == true
end

function Search:ConsumeAbandonedEvent()
	if self:GetRequestBarrierRemaining() <= 0 then
		return false
	end
	self.abandonedUntil = nil
	self.abandonedContext = nil
	self.barrier = nil
	return true
end

function Search:ClearAggregatedResultIDs()
	clearAggregate(self)
end

function Search:GetAggregatedResultIDs()
	return self.aggregateResultIDs,
		self.aggregateTotal,
		self.aggregateInfoByID,
		self.aggregateMemberCountsByID
end

local function importCompatibleQuestState(owner)
	if NativeSearch and NativeSearch.SetActiveQuestID then
		NativeSearch:SetActiveQuestID(owner.nativeQuestSearchActive)
	end
end

local function exportCompatibleQuestState(owner)
	if NativeSearch and NativeSearch.GetActiveQuestID then
		owner.nativeQuestSearchActive = NativeSearch:GetActiveQuestID()
	else
		owner.nativeQuestSearchActive = nil
	end
end

function Search:ReleaseNativeSearchSelection()
	return NativeSearch and NativeSearch.ReleaseSearchSelection
		and NativeSearch:ReleaseSearchSelection() or false
end

function Search:BuildScopes(selection, context)
	local rawScopes
	if GF.NavData and GF.NavData.ResolveSearchScopes then
		rawScopes = GF.NavData.ResolveSearchScopes(selection, { forSearch = true })
	elseif selection and GF.NavData and GF.NavData.ResolveSearchScope then
		rawScopes = {
			GF.NavData.ResolveSearchScope(selection, { forSearch = true }),
		}
	elseif selection then
		rawScopes = { selection }
	else
		rawScopes = {}
	end

	local scopes = {}
	for _, scope in ipairs(rawScopes or {}) do
		local normalized = normalizeScope(selection, scope)
		if normalized then
			scopes[#scopes + 1] = normalized
		end
	end
	scopes = mergeNormalizedScopes(scopes)
	if GF.LFGWorkspacePolicy and GF.LFGWorkspacePolicy.ConstrainSearchScopes then
		scopes = GF.LFGWorkspacePolicy:ConstrainSearchScopes(
			context and context.workspaceID,
			selection,
			scopes
		)
	end
	return scopes
end

function Search:ClearNativeQuestSearch()
	if self.nativeQuestSearchActive == nil then
		if NativeSearch and NativeSearch.SetActiveQuestID then
			NativeSearch:SetActiveQuestID(nil)
		end
		return true
	end
	if not (NativeSearch and NativeSearch.ClearQuestSearch) then
		return false
	end
	importCompatibleQuestState(self)
	local cleared = NativeSearch:ClearQuestSearch()
	exportCompatibleQuestState(self)
	return cleared == true
end

function Search:SuspendNativeQuestSearch()
	if self.nativeQuestSearchActive == nil then
		if NativeSearch and NativeSearch.SetActiveQuestID then
			NativeSearch:SetActiveQuestID(nil)
		end
		return true
	end
	if not (NativeSearch and NativeSearch.SuspendQuestSearch) then
		return false
	end
	importCompatibleQuestState(self)
	local suspended = NativeSearch:SuspendQuestSearch()
	exportCompatibleQuestState(self)
	return suspended == true
end

function Search:PrepareNativeQuestSearch(questID)
	questID = GF.QuestSearch and GF.QuestSearch.NormalizeQuestID
		and GF.QuestSearch:NormalizeQuestID(questID) or nil
	if not questID or not (NativeSearch and NativeSearch.PrepareQuestSearch) then
		return false
	end
	importCompatibleQuestState(self)
	local prepared = NativeSearch:PrepareQuestSearch(questID)
	exportCompatibleQuestState(self)
	return prepared == true
end

local function scopeNeedsAggregatedResults(scope)
	return scope and scope.resultActivityIDsFilter
		and #scope.resultActivityIDsFilter > 0
end

function Search:_RunScope(scope)
	if not scope or not scope.categoryID then
		return false
	end
	if GF.Availability and GF.Availability.ShouldProcessLfgEvent
		and not GF.Availability:ShouldProcessLfgEvent()
	then
		return false
	end
	if not (NativeSearch and NativeSearch.StartSearch) then
		return false
	end
	importCompatibleQuestState(self)
	local started = NativeSearch:StartSearch(scope)
	exportCompatibleQuestState(self)
	if started then
		self:_RecordNativeSearchStart()
	end
	return started == true
end

function Search:_RunPendingScope()
	local pending = self.pending
	if not pending then
		return false
	end
	return self:_RunScope(pending.scopes[1])
end

function Search:GetContext()
	return self.context
end

function Search:MatchesContext(context)
	local active = self.context
	if not active or not context then
		return false
	end
	return active.key == context.key
		and active.workspaceID == context.workspaceID
		and tonumber(active.generation) == tonumber(context.generation)
		and tonumber(active.searchToken) == tonumber(context.searchToken)
end

function Search:_CreateSession(context, scopes, aggregation)
	self._sessionSequence = (tonumber(self._sessionSequence) or 0) + 1
	local sessionID = self._sessionSequence
	return {
		id = sessionID,
		token = context and context.searchToken or sessionID,
		context = context,
		scopes = scopes,
		scope = scopes[1],
		state = "searching",
		aggregation = aggregation,
	}
end

function Search:Run(selection, context)
	if self.inFlight
		or (self.session and self.session.state == "searching")
	then
		self:AbandonActiveRequest()
		return false
	end
	if self:GetRequestBarrierRemaining() > 0
		or self:GetCooldownRemaining() > 0
	then
		return false
	end

	local reusableAggregateInfo = self.aggregateInfoByID
	local needsFreshAggregateInfo = false
	if GF.Result and GF.Result.NeedsFreshSearchResultInfo then
		needsFreshAggregateInfo = GF.Result:NeedsFreshSearchResultInfo()
	elseif GF.Result and GF.Result.NeedsPostFilters then
		needsFreshAggregateInfo = GF.Result:NeedsPostFilters()
	end
	local canReuseAggregateInfo = reusableAggregateInfo ~= nil
		and needsFreshAggregateInfo ~= true

	self:Reset()
	if GF.FindGroup and GF.FindGroup.IsSearchableSelection
		and not GF.FindGroup:IsSearchableSelection(selection)
	then
		return false
	end
	local scopes = self:BuildScopes(selection, context)
	-- Retail has one restricted result store. A second native request cannot be
	-- started by a result event or timer after the user's click chain ends.
	if #scopes ~= 1 then
		return false
	end

	local aggregation
	if scopeNeedsAggregatedResults(scopes[1]) then
		aggregation = {
			scopes = scopes,
			resultIDs = {},
			seen = {},
			infoByID = {},
			memberCountsByID = {},
			reusableInfoByID = canReuseAggregateInfo
				and reusableAggregateInfo or nil,
			total = 0,
		}
	end

	local session = self:_CreateSession(context, scopes, aggregation)
	self:_SetSession(session)
	if MemoryDiagnostics and MemoryDiagnostics.BeginSearch then
		MemoryDiagnostics:BeginSearch(#scopes)
	end

	local started
	if aggregation then
		started = self:_RunPendingScope()
	else
		started = self:_RunScope(scopes[1])
	end
	if not started then
		self:Reset()
	end
	return started == true
end

local function resultMatchesActivitySet(info, activitySet)
	if not info then
		return false
	end
	if type(info.activityIDs) == "table" then
		for _, activityID in ipairs(info.activityIDs) do
			if activityID and activitySet[activityID] == true then
				return true
			end
		end
	end
	local activityID = GF.SearchResultSnapshot
		and GF.SearchResultSnapshot.GetPrimaryActivityID
		and GF.SearchResultSnapshot.GetPrimaryActivityID(info)
	if not activityID then
		activityID = info.activityID
	end
	return activityID and activitySet[activityID] == true or false
end

local function buildActivityIDSet(activityIDs)
	if not activityIDs or #activityIDs == 0 then
		return nil
	end
	local set = {}
	for _, activityID in ipairs(activityIDs) do
		if activityID then
			set[activityID] = true
		end
	end
	return set
end

local function readSearchResultInfo(resultID)
	return NativeSearch and NativeSearch.GetSearchResultInfo
		and NativeSearch:GetSearchResultInfo(resultID) or nil
end

local function getSearchResultInfo(resultID)
	if not resultID or not (NativeSearch
		and NativeSearch.CanReadSearchResultInfo
		and NativeSearch:CanReadSearchResultInfo())
	then
		return nil
	end
	if MemoryDiagnostics and MemoryDiagnostics.current then
		MemoryDiagnostics:Add("freshSearchInfo", 1)
	end
	if MemoryDiagnostics and MemoryDiagnostics.current
		and MemoryDiagnostics.MeasureFirstReturn
	then
		return MemoryDiagnostics:MeasureFirstReturn(
			"freshSearchInfo",
			readSearchResultInfo,
			resultID
		)
	end
	return readSearchResultInfo(resultID)
end

function Search:OnSearchResults()
	local pending = self.pending
	if not pending then
		self:_CompleteSession()
		return "complete"
	end

	local scope = pending.scopes[1]
	local resultActivitySet = buildActivityIDSet(
		scope and scope.resultActivityIDsFilter)
	local total, resultIDs = readCurrentResultIDs()
	local scopeKept, scopeReused = 0, 0
	for _, resultID in ipairs(resultIDs or {}) do
		local info = pending.reusableInfoByID
			and pending.reusableInfoByID[resultID]
		if info then
			scopeReused = scopeReused + 1
		end
		local keep = true
		if resultActivitySet then
			info = info or getSearchResultInfo(resultID)
			keep = resultMatchesActivitySet(info, resultActivitySet)
		end
		if keep then
			scopeKept = scopeKept + 1
			if not pending.seen[resultID] then
				pending.seen[resultID] = true
				pending.resultIDs[#pending.resultIDs + 1] = resultID
				pending.total = (pending.total or 0) + 1
			end
			if resultID and NativeSearch:CanReadSearchResultInfo()
				and not pending.infoByID[resultID]
			then
				local capturedInfo = info or getSearchResultInfo(resultID)
				if capturedInfo and GF.ResolveSearchResultSocialCounts then
					GF.ResolveSearchResultSocialCounts(capturedInfo, resultID)
				end
				local compactedInfo = capturedInfo
				if capturedInfo and GF.SearchResultSnapshot
					and GF.SearchResultSnapshot.CompactSearchResultInfo
				then
					compactedInfo = GF.SearchResultSnapshot.CompactSearchResultInfo(
						capturedInfo, true)
					if compactedInfo ~= capturedInfo and MemoryDiagnostics
						and MemoryDiagnostics.current
					then
						MemoryDiagnostics:Add("summariesCompacted", 1)
					end
				end
				pending.infoByID[resultID] = compactedInfo
			end
			local compactedInfo = pending.infoByID[resultID]
			if resultID and type(compactedInfo) == "table" then
				-- A reused summary may retain identity projections from an older
				-- request. The current native store is authoritative for membership.
				compactedInfo._gfBlocklistPlayers = nil
				compactedInfo._gfBlocklistPlayersComplete = nil
			end
		end
	end
	if MemoryDiagnostics and MemoryDiagnostics.current then
		MemoryDiagnostics:RecordScope(
			total, #resultIDs, scopeKept, scopeReused)
	end

	self.aggregate = {
		resultIDs = pending.resultIDs,
		total = #pending.resultIDs,
		infoByID = pending.infoByID,
		memberCountsByID = pending.memberCountsByID,
	}
	self.aggregateResultIDs = self.aggregate.resultIDs
	self.aggregateTotal = self.aggregate.total
	self.aggregateInfoByID = self.aggregate.infoByID
	self.aggregateMemberCountsByID = self.aggregate.memberCountsByID
	self:_CompleteSession()
	return "complete"
end

function Search:OnSearchFailed()
	if MemoryDiagnostics and MemoryDiagnostics.AbortSearch then
		MemoryDiagnostics:AbortSearch("search-failed")
	end
	self:_SetSession(nil)
	clearAggregate(self)
end
