--!nocheck
-- searph/strategy.lua — move/policy engine for the BedWars module.
--
-- Contract
--   Snapshot() -> plain read model (no decisions, no side effects)
--   Evaluate(snapshot) -> state string
--   Decide(snapshot) -> ONE action table
--   Tick() -> snapshot, action, executed?
--
-- The server owns hit/damage/respawn. This engine only chooses what the client
-- asks for next; every write goes through the game's own controllers.

local Actor = {}
Actor.__index = Actor

-- Tunables. Values are in studs / seconds; named so they can be tuned live.
Actor.Config = {
	Interval = 0.10,        -- decision rate (10 Hz)
	FightRange = 14,        -- start fighting inside this
	ChaseRange = 26,        -- start closing inside this
	KiteHealth = 0.30,      -- retreat below this fraction of max health
	KiteRange = 22,         -- only kite a threat this close
	DefendRange = 34,       -- enemies this close to our bed trigger defend
	BedBreakRange = 6,      -- stand this close, then break
	BedReserve = 16,        -- blocks kept out of bridging
	BridgeMaxGap = 9,       -- bridge across gaps shorter than this
	FarmHealth = 0.60,      -- top up below this when no threat is near
	RepathCooldown = 0.35,
	-- Aim: the head line. Camera turns onto the head part, never the torso.
	Aim = true,
	AimPart = "Head",
	AimSmooth = 0.45,       -- 0 = instant snap, 1 = never arrives
	AimFov = 140,           -- degrees; outside this the turn is skipped
	-- Rush gate. Rushing before a real weapon is how you donate your economy:
	-- stone-or-better sword, or the match has run long enough that sitting is
	-- its own loss (the 2-minute inflection).
	-- Threshold is grounded in the live ItemMeta dump (2026-11-27): wood_sword
	-- 20, stone 25, iron 30, diamond 42, emerald 55, and mage's wizard_stick
	-- only 15 — so a mage never passes this gate on gear and must earn the
	-- rush via RushAfterSeconds instead.
	RushMinSwordDamage = 25,
	RushAfterSeconds = 150,
	-- Mage (Whim) deals -20% sword damage and takes +10% damage from all
	-- sources (BedwarsKitMeta description, live dump). It retreats earlier
	-- than other kits by this fraction of max health.
	MageKiteBonus = 0.10,
	-- Shop trips (dump 13 ground truth: prices, site tags, buy remote in
	-- navigation.lua Actuator.Buy). Trip thresholds per ore; ShopTravelRange
	-- is how far from the shop stand the actor still walks to it.
	ShopAtIron = 40,
	ShopAtGold = 8,
	ShopAtEmerald = 2,
	ShopAtDiamond = 4,
	ShopTravelRange = 8,
	-- Generator farming (dump 11 ground truth): diamond gens tick every 35s
	-- (tier 3: 32s, tier 5: 30s, stack 5-6); emerald 70s (tier 5: 25s,
	-- stack 3-5). Standing at a gen beats idling at bed. Scan throttled.
	GenScanInterval = 2,
	GenStandRange = 6,
}

-- Mode shapes the policy. BedWars spreads the same rules across three table
-- sizes; what changes is how much a death costs and whether a bed is shared.
Actor.Modes = {
	Solos = {
		kiteHealth = 0.35, kiteRange = 24, defendRange = 0,
		fightRange = 13, farmHealth = 0.70, aggression = 1.15,
	},
	Duos = {
		kiteHealth = 0.30, kiteRange = 22, defendRange = 30,
		fightRange = 14, farmHealth = 0.60, aggression = 1.0,
	},
	Squads = {
		kiteHealth = 0.26, kiteRange = 20, defendRange = 38,
		fightRange = 15, farmHealth = 0.55, aggression = 0.95,
	},
}

function Actor.ModeFor(teamSize)
	if teamSize >= 4 then
		return "Squads"
	elseif teamSize == 3 or teamSize == 2 then
		return "Duos"
	end
	return "Solos"
end

local KINDS = {
	Idle = "Idle",
	Travel = "Travel",
	Chase = "Chase",
	Attack = "Attack",
	Kite = "Kite",
	TravelBed = "TravelBed",
	BreakBed = "BreakBed",
	Bridge = "Bridge",
	Defend = "Defend",
	Farm = "Farm",
	FarmGen = "FarmGen",
	Shop = "Shop",
	Buy = "Buy",
	Upgrade = "Upgrade",
}

local function vec(p)
	return typeof(p) == "Vector3" and p or nil
end

local function flatDistance(a, b)
	local d = Vector3.new(a.X - b.X, 0, a.Z - b.Z)
	return d.Magnitude, d
end

local function rootOf(ent)
	return ent and (ent.RootPart or ent.HumanoidRootPart) or nil
end

-- ===========================================================================
-- Read model
-- ===========================================================================

local function readSelf(deps)
	local entitylib = deps.entitylib
	local character = entitylib.character
	if not character or not character.Parent then
		return nil
	end
	local root = character:FindFirstChild("HumanoidRootPart")
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if not root or not humanoid then
		return nil
	end
	return {
		character = character,
		root = root,
		humanoid = humanoid,
		position = root.Position,
		velocity = root.AssemblyLinearVelocity,
		health = humanoid.Health,
		maxHealth = math.max(1, humanoid.MaxHealth),
		team = deps.localPlayer.Team,
		teamName = deps.localPlayer:GetAttribute("Team"),
		alive = humanoid.Health > 0,
		walkSpeed = humanoid.WalkSpeed,
		hipHeight = humanoid.HipHeight,
	}
end

-- Same team, alive, Targetable -- the squad that shares your bed.
-- Team is the server's own attribute (Player.Team is the lobby team, which is
-- not the same thing in BedWars), so this reads GetAttribute("Team") first.
local function readAllies(deps, selfState)
	local entitylib = deps.entitylib
	local list = {}
	if not selfState then
		return list
	end
	local myTeam = selfState.teamName
	for _, ent in entitylib.List do
		local player = ent.Player
		if not player or player == deps.localPlayer then
			continue
		end
		local root = rootOf(ent)
		if not root then
			continue
		end
		local team = player:GetAttribute("Team")
		local teammates = false
		if myTeam ~= nil and team ~= nil then
			teammates = tostring(team) == tostring(myTeam)
		elseif player.Team and selfState.team then
			teammates = player.Team == selfState.team
		end
		if not teammates then
			continue
		end
		table.insert(list, {
			entity = ent,
			player = player,
			position = root.Position,
			health = ent.Health or 0,
			distance = flatDistance(selfState.position, root.Position),
		})
	end
	return list
end

local function readEnemies(deps, selfState)
	local entitylib = deps.entitylib
	local list = {}
	if not selfState then
		return list
	end
	for _, ent in entitylib.List do
		if not ent.Targetable then
			continue
		end
		local root = rootOf(ent)
		if not root then
			continue
		end
		local sameTeam = false
		if ent.Player and selfState.team and ent.Player.Team then
			sameTeam = ent.Player.Team == selfState.team
		end
		if sameTeam then
			continue
		end
		local dist = flatDistance(selfState.position, root.Position)
		-- Head line: the hit point is the head part when the entity carries one,
		-- the root otherwise. Never the torso -- the head is the smaller target
		-- and the one a swing should be aimed through.
		local head = ent[Actor.Config.AimPart] or root
		table.insert(list, {
			entity = ent,
			player = ent.Player,
			position = root.Position,
			head = head.Position,
			health = ent.Health or 0,
			maxHealth = ent.MaxHealth or 0,
			distance = dist,
			velocity = root.AssemblyLinearVelocity,
		})
	end
	table.sort(list, function(a, b)
		return a.distance < b.distance
	end)
	return list
end

local function readInventory(deps)
	local bedwars = deps.bedwars
	local store = deps.store
	local wool, woolCount, sword, swordDamage = nil, 0, nil, 0
	local container = deps.inventory
	if not container then
		return { wool = nil, woolCount = 0, sword = nil }
	end
	for _, item in container do
		if type(item) ~= "table" or not item.itemType then
			continue
		end
		if string.find(item.itemType, "wool", 1, true) then
			local amount = tonumber(item.amount) or 0
			if amount > woolCount then
				wool, woolCount = item.itemType, amount
			end
		end
		local meta = bedwars and bedwars.ItemMeta and bedwars.ItemMeta[item.itemType]
		local swordMeta = meta and meta.sword
		if swordMeta and (swordMeta.damage or 0) > swordDamage then
			sword, swordDamage = item, swordMeta.damage or 0
		end
	end
	return {
		wool = wool,
		woolCount = woolCount,
		sword = sword,
		swordDamage = swordDamage,
	}
end

-- Wallet: currencies are inventory stacks (InventoryUtil items =
-- {itemType, amount}); exact match on the four ores.
local CURRENCY_KEYS = { iron = "iron", gold = "gold", emerald = "emerald", diamond = "diamond" }

local function readCurrencies(deps)
	local wallet = { iron = 0, gold = 0, emerald = 0, diamond = 0 }
	local container = deps.inventory
	if not container then
		return wallet
	end
	for _, item in container do
		if type(item) == "table" and item.itemType and CURRENCY_KEYS[item.itemType] then
			wallet[item.itemType] += tonumber(item.amount) or 0
		end
	end
	return wallet
end

local function partPosition(instance)
	if not instance then
		return nil
	end
	local ok, pos = pcall(function()
		if instance:IsA("BasePart") then
			return instance.Position
		end
		local primary = instance.PrimaryPart
		return primary and primary.Position or nil
	end)
	return ok and pos or nil
end

-- Generators (dump 11): tagged "Generator" with an Id attribute; the part
-- itself is the pad. Scan throttled by Config.GenScanInterval.
local function scanGenerators(deps)
	local collection = deps.collection
	local list = {}
	if not collection then
		return list
	end
	pcall(function()
		for _, gen in collection:GetTagged("Generator") do
			local pos = partPosition(gen)
			if pos then
				table.insert(list, { id = gen:GetAttribute("Id"), position = pos })
			end
		end
	end)
	return list
end

local function nearestGenerator(deps, store, selfState)
	local now = os.clock()
	local cache = store.__genCache
	if type(cache) ~= "table" or now - (cache.at or 0) >= Actor.Config.GenScanInterval then
		cache = { at = now, list = scanGenerators(deps) }
		store.__genCache = cache
	end
	if not selfState then
		return nil
	end
	local best, bestDist = nil, math.huge
	for _, gen in cache.list do
		local dist = flatDistance(selfState.position, gen.position)
		if dist < bestDist then
			best, bestDist = { id = gen.id, position = gen.position, distance = dist }, dist
		end
	end
	return best
end

-- Shop sites (navigation.lua Observer.Sites ground truth): item shops are
-- tagged "BedwarsItemShop" with a child merchant ("desertMerchant") whose Id
-- attribute is the shopId; stand 7 studs out along its facing. Team upgrades
-- are tagged "TeamUpgradeShopkeeper"; stand 5 studs out.
local SITE_SCAN_INTERVAL = 0.5

local function standInFront(primary, pos, studs)
	local look = primary.CFrame.LookVector
	local flat = Vector3.new(look.X, 0, look.Z)
	if flat.Magnitude < 0.05 then
		return pos
	end
	return pos + flat.Unit * studs
end

local function scanSites(deps, store)
	local now = os.clock()
	local cache = store.__siteCache
	if type(cache) == "table" and now - (cache.at or 0) < SITE_SCAN_INTERVAL then
		return cache.sites
	end
	local sites = { list = {} }
	local collection = deps.collection
	if collection then
		pcall(function()
			for _, tagged in collection:GetTagged("BedwarsItemShop") do
				local npc = tagged:FindFirstChild("desertMerchant") or tagged
				local primary = npc:IsA("BasePart") and npc or npc.PrimaryPart or tagged
				local pos = partPosition(primary)
				if pos then
					table.insert(sites.list, {
						kind = "shop",
						id = npc:GetAttribute("Id"),
						position = pos,
						stand = standInFront(primary, pos, 7),
					})
				end
			end
			for _, tagged in collection:GetTagged("TeamUpgradeShopkeeper") do
				local primary = tagged:IsA("BasePart") and tagged or tagged.PrimaryPart or tagged
				local pos = partPosition(primary)
				if pos then
					table.insert(sites.list, {
						kind = "upgrades",
						id = tagged:GetAttribute("Id") or "upgrades",
						position = pos,
						stand = standInFront(primary, pos, 5),
					})
				end
			end
		end)
	end
	store.__siteCache = { at = now, sites = sites }
	return sites
end

local function nearestSite(deps, store, selfState, kind)
	local sites = scanSites(deps, store)
	if not selfState or not sites or not sites.list then
		return nil
	end
	local best, bestDist = nil, math.huge
	for _, site in sites.list do
		if site.kind == kind then
			local dist = flatDistance(selfState.position, site.position)
			if dist < bestDist then
				best, bestDist = { kind = site.kind, id = site.id, position = site.position, stand = site.stand, distance = dist }, dist
			end
		end
	end
	return best
end

-- Beds are owned by the Store, not by this engine. `Store.Beds` is the only
-- table read, `Store.BedScanAt` is the only clock, and `Store.BedProvider`
-- (optional) lets a host module supply the list instead -- when it is set this
-- engine stops scanning entirely.
--
-- Attribute names are probed, never assumed: the tag list is the game's
-- (navigation.lua reads CollectionService:GetTagged("bed")), but which
-- attribute carries ownership and which carries the shield differs per map
-- build. Unknown ownership is recorded as teamKnown = false and the policy
-- refuses to rush it, so a wrong guess can never send the actor at its own bed.
local BED_SCAN_INTERVAL = 0.4

Actor.BedTeamAttributes = { "TeamId", "Team", "team", "TeamName", "Owner", "owner" }
Actor.BedShieldAttributes = { "BedShieldEndTime", "ShieldEndTime", "BedShield", "Shield" }
Actor.BedTag = "bed"

local function firstAttribute(part, names)
	for _, name in names do
		local ok, value = pcall(function()
			return part:GetAttribute(name)
		end)
		if ok and value ~= nil then
			return value, name
		end
	end
	return nil, nil
end

-- Owner can also live on the bed's ancestor when the tagged part is a cell.
local function resolveOwner(part)
	local value, name = firstAttribute(part, Actor.BedTeamAttributes)
	if value ~= nil then
		return tostring(value), name
	end
	local parent = part.Parent
	local depth = 0
	while parent and depth < 3 do
		value, name = firstAttribute(parent, Actor.BedTeamAttributes)
		if value ~= nil then
			return tostring(value), name
		end
		parent = parent.Parent
		depth += 1
	end
	return nil, nil
end

local function resolveShield(part)
	local value = firstAttribute(part, Actor.BedShieldAttributes)
	if value ~= nil then
		return tonumber(value) or 0
	end
	local parent = part.Parent
	if parent then
		value = firstAttribute(parent, Actor.BedShieldAttributes)
		if value ~= nil then
			return tonumber(value) or 0
		end
	end
	return 0
end

function Actor.SetBedProvider(store, provider)
	if not store then
		return
	end
	store.BedProvider = provider
	if getgenv then
		getgenv().searphBedProvider = provider
	end
end

local function refreshBeds(deps, store, selfState)
	local cache = store.Beds
	if type(cache) ~= "table" then
		cache = {}
		store.Beds = cache
	end

	-- A host provider owns the list; this engine only reads it.
	if type(store.BedProvider) == "function" then
		local ok, list = pcall(store.BedProvider, selfState)
		if ok and type(list) == "table" then
			return list
		end
		return cache
	end

	local now = os.clock()
	if type(store.BedScanAt) == "number" and now - store.BedScanAt < BED_SCAN_INTERVAL then
		return cache
	end
	store.BedScanAt = now

	local collection = deps.collection
	if not collection then
		return cache
	end

	table.clear(cache)
	local myTeam = selfState and selfState.teamName or nil
	for _, part in collection:GetTagged(Actor.BedTag) do
		local ok, pos = pcall(function()
			return part.Position
		end)
		if not ok or not pos then
			continue
		end
		local owner = resolveOwner(part)
		table.insert(cache, {
			team = owner,
			teamKnown = owner ~= nil,
			position = pos,
			block = part,
			shieldEndTime = resolveShield(part),
			mine = owner ~= nil and myTeam ~= nil and owner == myTeam,
		})
	end
	return cache
end

local function readBeds(deps, selfState)
	local out = {}
	if not selfState then
		return out
	end
	local beds = deps.__beds or {}
	for _, bed in beds do
		local pos = vec(bed.position)
		if not pos then
			continue
		end
		local dist = flatDistance(selfState.position, pos)
		table.insert(out, {
			position = pos,
			team = bed.team,
			teamKnown = bed.teamKnown == true,
			block = bed.block,
			shieldEndTime = bed.shieldEndTime,
			distance = dist,
			mine = bed.mine == true,
		})
	end
	table.sort(out, function(a, b)
		return a.distance < b.distance
	end)
	return out
end

function Actor.Snapshot(store, deps)
	local selfState = readSelf(deps)
	deps.__beds = refreshBeds(deps, store, selfState)
	local snapshot = {
		time = os.clock(),
		matchState = store.MatchState or 0,
		-- Match clock: stamped on the first live tick, cleared whenever the
		-- server stops reporting a live match.
		matchTime = 0,
		self = selfState,
		enemies = {},
		beds = {},
		inventory = readInventory(deps),
		currency = { iron = 0, gold = 0, emerald = 0, diamond = 0 },
		generator = nil,
		sites = nil,
		shopSite = nil,
		upgradeSite = nil,
		upgradeTiers = {},
	}
	if snapshot.matchState == 1 then
		if not store.MatchStartAt then
			store.MatchStartAt = os.clock()
		end
		snapshot.matchTime = os.clock() - store.MatchStartAt
	else
		store.MatchStartAt = nil
	end

	if not selfState or not selfState.alive then
		return snapshot
	end
	snapshot.enemies = readEnemies(deps, selfState)
	snapshot.allies = readAllies(deps, selfState)
	-- Solos / Duos / Squads straight from how many share the team.
	local teamPlayers = deps.localPlayer:GetAttribute("Team")
	if teamPlayers ~= nil and deps.players then
		local count = 0
		for _, other in deps.players:GetPlayers() do
			if tostring(other:GetAttribute("Team")) == tostring(teamPlayers) then
				count += 1
			end
		end
		snapshot.teamSize = math.max(1, count)
	else
		snapshot.teamSize = 1 + #snapshot.allies
	end
	snapshot.mode = Actor.ModeFor(snapshot.teamSize)
	-- Kit state from the Store's game-mirroring predicate (PlayingAsKits +
	-- ExtraKit_<kit>, Kit Fusion safe). pcall-guarded: a host without kit
	-- support just runs kit-neutral policy.
	snapshot.kits = {}
	snapshot.kitMage = false
	if type(store.HasKit) == "function" then
		if type(store.ActiveKits) == "function" then
			local okKits, kitList = pcall(store.ActiveKits)
			if okKits and type(kitList) == "table" then
				snapshot.kits = kitList
			end
		end
		local okMage, isMage = pcall(store.HasKit, "mage")
		snapshot.kitMage = okMage and isMage == true
	end
	snapshot.beds = readBeds(deps, selfState)
	snapshot.currency = readCurrencies(deps)
	snapshot.generator = nearestGenerator(deps, store, selfState)
	snapshot.sites = scanSites(deps, store)
	snapshot.shopSite = nearestSite(deps, store, selfState, "shop")
	snapshot.upgradeSite = nearestSite(deps, store, selfState, "upgrades")
	snapshot.upgradeTiers = Actor.UpgradeTiers(deps, store)
	snapshot.myBed = nil
	snapshot.enemyBed = nil
	-- Only a bed with a resolved owner may become "mine" or "enemy". An
	-- unresolved owner is neither: the policy runs defensively instead of
	-- guessing and possibly marching at our own bed.
	for _, bed in snapshot.beds do
		if bed.teamKnown then
			if bed.mine and not snapshot.myBed then
				snapshot.myBed = bed
			elseif not bed.mine and not snapshot.enemyBed then
				snapshot.enemyBed = bed
			end
		end
	end
	return snapshot
end

-- ===========================================================================
-- Policy
-- ===========================================================================

local function nearest(state, list, range)
	for _, item in list do
		if item.distance <= range then
			return item
		end
	end
	return nil
end

function Actor.Evaluate(snapshot)
	local cfg = Actor.Config
	local mode = Actor.Modes[snapshot.mode or "Solos"] or Actor.Modes.Solos
	local selfState = snapshot.self

	if snapshot.matchState ~= 1 then
		return "Lobby"
	end
	if not selfState or not selfState.alive then
		return "Dead"
	end

	local healthFraction = selfState.health / selfState.maxHealth
	local threat = nearest(nil, snapshot.enemies, mode.kiteRange)

	-- Mage takes +10% damage from everything: bail earlier.
	local kiteHealth = mode.kiteHealth + (snapshot.kitMage and cfg.MageKiteBonus or 0)
	if threat and healthFraction <= kiteHealth then
		return "Kite"
	end

	-- Solos has no teammate to cover a bed, so there is nothing to defend but
	-- yourself; defendRange = 0 disables the branch entirely.
	local myBed = snapshot.myBed
	if myBed and mode.defendRange > 0 then
		for _, enemy in snapshot.enemies do
			if flatDistance(enemy.position, myBed.position) <= mode.defendRange then
				return "Defend"
			end
		end
	end

	local fighter = nearest(nil, snapshot.enemies, mode.fightRange)
	if fighter then
		return "Fight"
	end

	if healthFraction <= mode.farmHealth and not threat then
		return "Farm"
	end

	-- Wallet full: the shop is the only sink. Checked after the combat gates
	-- so a fight always outranks a shopping trip.
	local currency = snapshot.currency or {}
	if (currency.iron or 0) >= cfg.ShopAtIron or (currency.gold or 0) >= cfg.ShopAtGold
		or (currency.emerald or 0) >= cfg.ShopAtEmerald or (currency.diamond or 0) >= cfg.ShopAtDiamond then
		return "Shop"
	end

	local chaser = nearest(nil, snapshot.enemies, cfg.ChaseRange)
	if chaser then
		return "Fight"
	end

	if snapshot.enemyBed then
		return "Rush"
	end

	return "Farm"
end

-- Shop prices from dump 13 (BedwarsShop.ShopItems, live server meta) and the
-- buy remote from navigation.lua Actuator.Buy. `once` items are recorded in
-- store.__bought after a successful fire; wool tops up to untilCount.
Actor.ShopPrices = {
	wool_white = { currency = "iron", price = 8, untilCount = 48 },
	telepearl = { currency = "emerald", price = 2, once = true },
	wizard_staff_2 = { currency = "emerald", price = 4, once = true },
	wizard_staff_3 = { currency = "emerald", price = 6, once = true, requires = "wizard_staff_2" },
	leather_chestplate = { currency = "iron", price = 50, once = true, skipIf = "diamond_chestplate" },
	diamond_chestplate = { currency = "emerald", price = 8, once = true },
	stone_pickaxe = { currency = "iron", price = 20, once = true },
}

-- Priority when several are affordable: damage first, then survivability,
-- then utility. Mage's wizard_stick is 15 dmg, so staff_2 is the top pick.
Actor.BuyOrder = {
	"wizard_staff_2",
	"diamond_chestplate",
	"wizard_staff_3",
	"wool_white",
	"stone_pickaxe",
	"telepearl",
	"leather_chestplate",
}

-- Team upgrades (dump 13 OGTeamUpgrades): the keys are the ids fired
-- verbatim via RequestPurchaseTeamUpgrade. Ordered cheapest/highest value
-- first; tiers are read from the bedwars store state, default 0.
Actor.UpgradeOrder = {
	{ id = "TEAM_GENERATOR", prices = { 4, 8, 12 } },
	{ id = "ARMOR", prices = { 4, 8, 20 } },
	{ id = "BREAK_SPEED", prices = { 3, 6 } },
}

-- Tier reader: bedwars.getStore(bedwars):getState().Bedwars.teamUpgrades is
-- keyed by team name. pcall the whole chain; anything missing means tier 0.
function Actor.UpgradeTiers(deps, store)
	local tiers = (store and store.__upgradeTiers) or {}
	local now = os.clock()
	if (store.__upgradeTiersAt or 0) and now - (store.__upgradeTiersAt or 0) < 1 then
		return tiers
	end
	store.__upgradeTiersAt = now
	local bedwars = deps.bedwars
	local ok, result = pcall(function()
		local gameState = bedwars.getStore and bedwars.getStore(bedwars) or bedwars.Store
		if not gameState or not gameState.getState then
			return nil
		end
		local state = gameState:getState()
		local team = deps.localPlayer:GetAttribute("Team")
		return state.Bedwars.teamUpgrades[tostring(team)]
	end)
	if ok and type(result) == "table" then
		for _, upgrade in Actor.UpgradeOrder do
			tiers[upgrade.id] = tonumber(result[upgrade.id]) or 0
		end
		store.__upgradeTiers = tiers
	end
	return tiers
end

-- Next affordable item, or nil. `once` honors store.__bought; wool honors
-- untilCount against the live inventory count of that item type.
function Actor.NextPurchase(store, deps, snapshot)
	local wallet = snapshot.currency or {}
	local bought = store.__bought or {}
	local counts = {}
	local container = deps.inventory
	if container then
		for _, item in container do
			if type(item) == "table" and item.itemType then
				counts[item.itemType] = (counts[item.itemType] or 0) + (tonumber(item.amount) or 0)
			end
		end
	end
	for _, name in Actor.BuyOrder do
		local entry = Actor.ShopPrices[name]
		if entry then
			local have = counts[name] or 0
			local done = (entry.once and bought[name]) or (entry.untilCount and have >= entry.untilCount)
			local gated = entry.requires and not (bought[entry.requires] or (counts[entry.requires] or 0) > 0)
			local superseded = entry.skipIf and bought[entry.skipIf]
			if not done and not gated and not superseded
				and (wallet[entry.currency] or 0) >= entry.price then
				return name, entry
			end
		end
	end
	return nil
end

-- Next affordable team upgrade, or nil.
function Actor.NextUpgrade(store, deps, snapshot)
	local wallet = snapshot.currency or {}
	local tiers = snapshot.upgradeTiers or {}
	for _, upgrade in Actor.UpgradeOrder do
		local tier = tiers[upgrade.id] or 0
		local price = upgrade.prices[tier + 1]
		if price and (wallet.diamond or 0) >= price then
			return upgrade.id, price
		end
	end
	return nil
end

local function safeMoveDirection(selfState, awayFrom)
	local delta = selfState.position - awayFrom
	local flat = Vector3.new(delta.X, 0, delta.Z)
	if flat.Magnitude < 0.01 then
		return Vector3.new(0, 0, 1)
	end
	return flat.Unit
end

function Actor.Decide(snapshot, store)
	local cfg = Actor.Config
	local state = Actor.Evaluate(snapshot)
	local selfState = snapshot.self
	local deps = store and store.__actor and store.__actor.deps or nil

	if state == "Lobby" then
		return { kind = KINDS.Idle, reason = "match not live" }
	end
	if state == "Dead" then
		return { kind = KINDS.Idle, reason = "respawning" }
	end

	if state == "Kite" then
		local mode = Actor.Modes[snapshot.mode or "Solos"] or Actor.Modes.Solos
		local threat = nearest(nil, snapshot.enemies, mode.kiteRange)
		if threat then
			local dir = safeMoveDirection(selfState, threat.position)
			return {
				kind = KINDS.Kite,
				position = selfState.position + dir * 18,
				target = threat.entity,
				reason = string.format("health %.0f%%, threat %.1f", 100 * selfState.health / selfState.maxHealth, threat.distance),
			}
		end
		return { kind = KINDS.Idle, reason = "kite with no threat" }
	end

	if state == "Defend" then
		local mode = Actor.Modes[snapshot.mode or "Solos"] or Actor.Modes.Solos
		local myBed = snapshot.myBed
		for _, enemy in snapshot.enemies do
			if flatDistance(enemy.position, myBed.position) <= mode.defendRange then
				if enemy.distance <= mode.fightRange then
					return { kind = KINDS.Attack, target = enemy.entity, aim = enemy.head, position = enemy.position, reason = "bed defender in reach" }
				end
				return { kind = KINDS.Chase, target = enemy.entity, position = enemy.position, reason = "bed defender out of reach" }
			end
		end
		return { kind = KINDS.Travel, position = myBed.position, reason = "return to bed" }
	end

	if state == "FarmGen" then
		local gen = snapshot.generator
		if gen then
			return { kind = KINDS.FarmGen, position = gen.position, reason = "at generator" }
		end
	end

	if state == "Fight" then
		local mode = Actor.Modes[snapshot.mode or "Solos"] or Actor.Modes.Solos
		local target = nearest(nil, snapshot.enemies, cfg.ChaseRange)
		if target then
			if target.distance <= mode.fightRange then
				return { kind = KINDS.Attack, target = target.entity, aim = target.head, position = target.position, reason = string.format("fight at %.1f studs", target.distance) }
			end
			return { kind = KINDS.Chase, target = target.entity, position = target.position, reason = string.format("closing from %.1f", target.distance) }
		end
	end

	if state == "Rush" then
		local bed = snapshot.enemyBed
		local gap = bed.distance
		-- No real weapon and the match is still young: keep farming instead of
		-- walking a wooden sword at a defended bed.
		local weaponReady = (snapshot.inventory.swordDamage or 0) >= cfg.RushMinSwordDamage
		local committed = (snapshot.matchTime or 0) >= cfg.RushAfterSeconds
		if not weaponReady and not committed then
			return { kind = KINDS.Farm, reason = string.format("waiting on gear (sword %.0f)", snapshot.inventory.swordDamage or 0) }
		end
		-- BedShieldEndTime is the server's own protection clock: while it is still
		-- ahead of the server clock the bed cannot take damage, so breaking it is
		-- wasted swings. Hold position and wait out the shield instead.
		local now = workspace:GetServerTimeNow()
		local shielded = (bed.shieldEndTime or 0) > now
		if shielded then
			return { kind = KINDS.Idle, position = bed.position, reason = string.format("bed shielded for %.1fs", (bed.shieldEndTime or 0) - now) }
		end
		if gap <= cfg.BedBreakRange then
			if bed.block then
				return { kind = KINDS.BreakBed, target = bed.block, position = bed.position, reason = "at enemy bed" }
			end
			return { kind = KINDS.BreakBed, position = bed.position, reason = "at enemy bed, block unresolved" }
		end
		local blocks = snapshot.inventory.woolCount
		if blocks > cfg.BedReserve and gap <= cfg.BridgeMaxGap then
			return { kind = KINDS.Bridge, position = bed.position, item = snapshot.inventory.wool, reason = string.format("bridging %.1f studs", gap) }
		end
		return { kind = KINDS.Travel, position = bed.position, reason = string.format("rushing bed at %.1f", gap) }
	end

	if state == "Shop" then
		-- Shop trips are real now: walk to the item shop stand (or the upgrade
		-- keeper when only an upgrade is affordable) and buy there. Nothing
		-- affordable falls through to the Farm/hold tail below.
		local deps = store and store.__actor and store.__actor.deps or nil
		local item, entry = deps and Actor.NextPurchase(store, deps, snapshot) or nil
		local upgradeId, upgradePrice = deps and Actor.NextUpgrade(store, deps, snapshot) or nil
		if item then
			local site = snapshot.shopSite
			if site then
				if site.distance > cfg.ShopTravelRange then
					return { kind = KINDS.Travel, position = site.stand, reason = string.format("to shop for %s (%.0f studs)", item, site.distance) }
				end
				return { kind = KINDS.Buy, item = item, entry = entry, siteId = site.id, position = site.stand, reason = string.format("buy %s for %d %s", item, entry.price, entry.currency) }
			end
		elseif upgradeId then
			local site = snapshot.upgradeSite
			if site then
				if site.distance > cfg.ShopTravelRange then
					return { kind = KINDS.Travel, position = site.stand, reason = string.format("to upgrades for %s (%.0f studs)", upgradeId, site.distance) }
				end
				return { kind = KINDS.Upgrade, upgradeId = upgradeId, price = upgradePrice, siteId = site.id, position = site.stand, reason = string.format("upgrade %s for %d dia", upgradeId, upgradePrice) }
			end
		end
	end

	-- Farm / hold
	local myBed = snapshot.myBed
	if myBed and myBed.distance > 12 then
		return { kind = KINDS.Travel, position = myBed.position, reason = "holding near bed" }
	end
	-- Stand at the nearest generator instead of idling: drops accumulate on
	-- the pad and walk to you (dump 11 cooldowns: diamond 30-35s, emerald
	-- 25-70s; island iron/gold tick faster than the rare ores).
	local gen = snapshot.generator
	if gen and gen.distance > cfg.GenStandRange then
		return { kind = KINDS.FarmGen, position = gen.position, reason = string.format("farming gen at %.1f", gen.distance) }
	end
	return { kind = KINDS.Idle, reason = "nothing actionable" }
end

-- ===========================================================================
-- Hands: the one executed action path
-- ===========================================================================

local Hands = {}
Actor.Hands = Hands

function Hands.Move(deps, position, snapshot)
	local humanoid = snapshot.self and snapshot.self.humanoid
	if not humanoid then
		return false, "no humanoid"
	end
	humanoid:MoveTo(position)
	return true
end

function Hands.Chase(deps, position, snapshot)
	return Hands.Move(deps, position, snapshot)
end

-- Turn the camera onto a world point, rate-limited and FOV-gated so the turn
-- never snaps backwards through 180 degrees on a stale target.
function Hands.Aim(deps, point)
	local cfg = Actor.Config
	if not cfg.Aim or not point then
		return false, "aim disabled"
	end
	local camera = workspace.CurrentCamera
	if not camera then
		return false, "no camera"
	end
	local origin = camera.CFrame.Position
	local toPoint = (point - origin)
	if toPoint.Magnitude < 0.5 then
		return false, "target on the lens"
	end
	local look = camera.CFrame.LookVector
	local angle = math.deg(math.acos(math.clamp(look:Dot(toPoint.Unit), -1, 1)))
	if angle > cfg.AimFov then
		return false, string.format("outside FOV (%.0f deg)", angle)
	end
	local goal = CFrame.lookAt(origin, point)
	camera.CFrame = camera.CFrame:Lerp(goal, 1 - cfg.AimSmooth)
	return true
end

function Hands.Attack(deps, target, aimPoint)
	local bedwars = deps.bedwars
	local ent = target
	if not ent then
		return false, "no target"
	end
	local root = rootOf(ent)
	if not root then
		return false, "target has no root"
	end
	if aimPoint then
		Hands.Aim(deps, aimPoint)
	end
	local controller = bedwars and bedwars.SwordController
	if controller then
		local ok = pcall(function()
			controller.lastAttack = workspace:GetServerTimeNow() - 1
		end)
		if ok then
			return true
		end
	end
	-- Fallback: activate whatever tool is held at the target.
	local character = deps.entitylib.character
	local tool = character and character:FindFirstChildOfClass("Tool")
	if tool then
		local ok = pcall(function()
			tool:Activate()
		end)
		if ok then
			return true
		end
	end
	return false, "no attack path"
end

function Hands.Place(deps, position, item)
	local bedwars = deps.bedwars
	if not bedwars or not bedwars.placeBlock then
		return false, "no block placer"
	end
	local ok, err = pcall(bedwars.placeBlock, position, item, false)
	return ok, err
end

function Hands.Break(deps, block, position)
	local bedwars = deps.bedwars
	if not bedwars then
		return false, "no bedwars table"
	end
	if block and bedwars.breakBlock then
		local ok, err = pcall(bedwars.breakBlock, block)
		return ok, err
	end
	if position and bedwars.BlockController then
		local store = bedwars.BlockController:getStore()
		if store then
			local cell = bedwars.BlockController:getBlockPosition(position)
			local target = store:getBlockAt(cell)
			if target and bedwars.breakBlock then
				local ok, err = pcall(bedwars.breakBlock, target)
				return ok, err
			end
		end
	end
	return false, "no block to break"
end

function Hands.Bridge(deps, position, item, snapshot)
	local selfState = snapshot.self
	if not selfState then
		return false, "no self"
	end
	local dir = position - selfState.position
	local flat = Vector3.new(dir.X, 0, dir.Z)
	if flat.Magnitude < 0.5 then
		return false, "already there"
	end
	flat = flat.Unit
	local placeAt = selfState.position + flat * 2 + Vector3.new(0, -2, 0)
	Hands.Move(deps, selfState.position + flat * 4, snapshot)
	return Hands.Place(deps, placeAt, item)
end

-- Buy remote, verbatim from navigation.lua Actuator.Buy: fire
-- BedwarsPurchaseItem with the shopItem the game itself derives. Guards:
-- wallet >= price, Current.price == Purchase.price, not disabled, not locked
-- by forge.
function Hands.Buy(deps, action)
	local bedwars = deps.bedwars
	if not bedwars or not bedwars.Shop or not bedwars.Handler then
		return false, "no bedwars.Shop/Handler"
	end
	local entry = action.entry
	if not entry then
		return false, "no entry"
	end
	local wallet = readCurrencies(deps)
	if (wallet[entry.currency] or 0) < entry.price then
		return false, string.format("wallet short: %d %s < %d", wallet[entry.currency] or 0, entry.currency, entry.price)
	end
	local ok, err = pcall(function()
		local shopItem = bedwars.Shop.getShopItem(action.item, deps.localPlayer)
		bedwars.Handler:Get("BedwarsPurchaseItem"):Fire("CallServerAsync", {
			shopItem = shopItem,
			shopId = action.siteId,
		})
	end)
	return ok, err
end

-- Team upgrades: RequestPurchaseTeamUpgrade fires the upgrade id verbatim
-- (dump 13 keys). Fire at the upgrade keeper's site.
function Hands.Upgrade(deps, action)
	local bedwars = deps.bedwars
	if not bedwars or not bedwars.Handler then
		return false, "no bedwars.Handler"
	end
	local ok, err = pcall(function()
		bedwars.Handler:Get("RequestPurchaseTeamUpgrade"):Fire("CallServerAsync", action.upgradeId)
	end)
	return ok, err
end

-- ===========================================================================
-- Actor
-- ===========================================================================

function Actor.new(store, deps)
	deps = deps or {}
	local vape = deps.vape or shared.vape
	local entitylib = deps.entitylib or (vape and vape.Libraries and vape.Libraries.entity)
	local env = getfenv and getfenv(0) or _G
	local bedwars = deps.bedwars or rawget(env, "bedwars") or (getgenv and getgenv().bedwars)

	if not entitylib then
		return nil
	end
	assert(store, "strategy: Store missing")

	local self_ = setmetatable({
		store = store,
		deps = {
			vape = vape,
			entitylib = entitylib,
			localPlayer = deps.localPlayer or game:GetService("Players").LocalPlayer,
			players = deps.players or game:GetService("Players"),
			bedwars = bedwars,
			store = store,
		},
		nextThink = 0,
		nextRepath = 0,
		players = deps.players or game:GetService("Players"),
		counters = { ticks = 0, executed = 0, failed = 0 },
		last = { kind = "Idle", reason = "init" },
		lastSnapshot = nil,
		enabled = true,
	}, Actor)

	local okCollection, collection = pcall(function()
		return game:GetService("CollectionService")
	end)
	self_.deps.collection = okCollection and collection or nil

	store.Actor = self_
	return self_
end

function Actor:Inventory()
	local deps = self.deps
	local bedwars = deps.bedwars
	if bedwars and bedwars.getInventory then
		local ok, inv = pcall(bedwars.getInventory, deps.localPlayer)
		if ok and type(inv) == "table" and inv.items then
			deps.inventory = inv.items
			return inv.items
		end
	end
	local legacy = self.store and self.store.Inventory
	deps.inventory = legacy and legacy.Inventory and legacy.Inventory.Items or {}
	return deps.inventory
end

function Actor:Pause()
	self.enabled = false
end

function Actor:Resume()
	self.enabled = true
end

function Actor:Tick(now)
	now = now or os.clock()
	if not self.enabled then
		return nil, nil
	end
	if now < self.nextThink then
		return nil, self.last
	end
	self.nextThink = now + Actor.Config.Interval

	local cfg = Actor.Config
	local store = self.store
	local deps = self.deps

	-- Refresh the bedwars handle once; extras builds it after Knit starts.
	if not deps.bedwars then
		local env = getfenv and getfenv(0) or _G
		deps.bedwars = rawget(env, "bedwars") or (getgenv and getgenv().bedwars)
	end

	self:Inventory()
	self.lastSnapshot = Actor.Snapshot(store, deps)
	local snapshot = self.lastSnapshot
	local action = Actor.Decide(snapshot, store)

	self.counters.ticks += 1
	self.last = action

	local ok, reason
	if action.kind == KINDS.Attack then
		ok, reason = Hands.Attack(deps, action.target, action.aim)
	elseif action.kind == KINDS.Chase or action.kind == KINDS.Travel or action.kind == KINDS.TravelBed
		or action.kind == KINDS.Kite or action.kind == KINDS.Defend or action.kind == KINDS.FarmGen then
		if now < self.nextRepath then
			return snapshot, action
		end
		self.nextRepath = now + cfg.RepathCooldown
		ok, reason = Hands.Move(deps, action.position, snapshot)
	elseif action.kind == KINDS.BreakBed then
		ok, reason = Hands.Break(deps, action.target, action.position)
	elseif action.kind == KINDS.Bridge then
		if now < self.nextRepath then
			return snapshot, action
		end
		self.nextRepath = now + cfg.RepathCooldown
		ok, reason = Hands.Bridge(deps, action.position, action.item, snapshot)
	elseif action.kind == KINDS.Buy then
		ok, reason = Hands.Buy(deps, action)
		if ok then
			store.__bought = store.__bought or {}
			store.__bought[action.item] = true
		end
	elseif action.kind == KINDS.Upgrade then
		ok, reason = Hands.Upgrade(deps, action)
	else
		return snapshot, action
	end

	if ok then
		self.counters.executed += 1
	else
		self.counters.failed += 1
		self.lastError = reason
	end
	return snapshot, action
end

function Actor:Status()
	local store = self.store
	local snapshot = self.lastSnapshot or { matchState = 0, enemies = {}, beds = {}, allies = {} }
	return {
		enabled = self.enabled,
		mode = snapshot.mode,
		teamSize = snapshot.teamSize,
		allies = snapshot.allies and #snapshot.allies or 0,
		state = Actor.Evaluate(snapshot),
		action = self.last,
		counters = self.counters,
		lastError = self.lastError,
		currency = snapshot.currency,
		generator = snapshot.generator and snapshot.generator.distance or nil,
		sites = snapshot.sites and snapshot.sites.list and #snapshot.sites.list or 0,
		shopSite = snapshot.shopSite and snapshot.shopSite.distance or nil,
		upgradeSite = snapshot.upgradeSite and snapshot.upgradeSite.distance or nil,
		upgradeTiers = snapshot.upgradeTiers,
		bought = store.__bought,
	}
end

-- ===========================================================================
-- Bootstrap: install onto the Store that bedwars.lua exports, if present.
-- ===========================================================================

function Actor.Install(store, deps)
	if not store then
		return nil
	end
	if store.__actor then
		return store.__actor
	end
	local actor = Actor.new(store, deps)
	if not actor then
		return nil
	end
	store.__actor = actor
	if getgenv then
		getgenv().searphActor = actor
	end

	-- One heartbeat drives the loop. Guarded so a teardown connection never
	-- leaves the actor ticking against a dead store.
	local ok, RunService = pcall(function()
		return game:GetService("RunService")
	end)
	if ok and RunService then
		actor.connection = RunService.RenderStepped:Connect(function()
			local tickOk, err = pcall(function()
				actor:Tick()
			end)
			if not tickOk then
				actor.counters.failed += 1
				actor.lastError = tostring(err)
			end
		end)
		if store and store.Clean and type(store.Clean) == "function" then
			store.Clean(actor.connection)
		end
	end

	return actor
end

local env = getgenv and getgenv() or _G
local bedwarsExport = env.slopBedwars or (env.searph and env.searph.bedwars)
if bedwarsExport and bedwarsExport.Store then
	Actor.Install(bedwarsExport.Store, bedwarsExport.deps)
end

return Actor
