import type { BlkBlock } from '@wto/blk'; import type { ItemCatalogue } from '../items/item-catalogue.ts'; import { applyUniversalSpares } from '../items/universal-spares.ts'; import { dailySparesLeft, recordDailySpare, usedDailySpare } from '../profile/profile-daily-spares.ts'; import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts'; import type { TechTree } from '../research/tech-tree.ts'; import type { BattleSession } from './battle-session-store.ts'; /** LocalMP uses a source token for an attached backup and the stock UID for an inventory item. */ const VEHICLE_BACKUP = 'vehicle'; export const DAILY_BACKUP = 'daily_free_spare'; export interface BackupSpawn { readonly slot: number; readonly unit: string; readonly backup: string; } function receiptKey(session: BattleSession, slot: number): string { return `${session.sessionId}_${slot}`; } export function recordDailyBackupSpawn(profile: BlkBlock, session: BattleSession, spawn: BackupSpawn): boolean { return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === spawn.unit && recordDailySpare(profile, session.startedAtSec, receiptKey(session, spawn.slot)); } /** Debit confirmed backup spawns from the lineup that the server sent at launch. */ export function consumeBattleSpares( profile: BlkBlock, session: BattleSession, spawns: readonly BackupSpawn[], items: ItemCatalogue, techTree: TechTree, ): Readonly> { const seenSlots = new Set(); const consumed = new Map(); for (const spawn of spawns) { const { slot, unit, backup } = spawn; if (session.spareSlots?.get(slot) !== unit || seenSlots.has(slot)) continue; seenSlots.add(slot); if (backup === DAILY_BACKUP) { recordDailyBackupSpawn(profile, session, spawn); continue; } if (dailySparesLeft(profile, session.startedAtSec) > 0 || usedDailySpare(profile, session.startedAtSec, receiptKey(session, slot))) continue; if (backup !== VEHICLE_BACKUP && !applyUniversalSpares(profile, items, techTree, backup, unit, 1).ok) continue; const owned = spareCount(profile, unit); if (owned < 1) continue; setSpareCount(profile, unit, owned - 1); consumed.set(unit, (consumed.get(unit) ?? 0) + 1); } return Object.fromEntries(consumed); }