import {
	cloneStack,
	insertStack,
	stackQuantity,
	takeFromSlot,
	INVENTORY_SLOTS
} from "../items/inventory.js";
import { itemDefinition } from "../definitions/items.js";
import { attachOrigins, normalizeOrigins, splitOrigins } from "../items/origin.js";

/**
 * How many additional empty bag slots a player would need after giving
 * `giveLines` and receiving `receiveStacks`. 0 = swap fits.
 *
 * @param {Array} inventorySlots
 * @param {Array<{ bagSlotIndex: number, quantity: number }>} giveLines
 * @param {Array} receiveStacks stacks the partner is offering (item payloads)
 */
export function inventorySlotsShortAfterTrade (inventorySlots, giveLines, receiveStacks)
{
	let next = (inventorySlots ?? []).map((slot) => cloneStack(slot));
	while (next.length < INVENTORY_SLOTS)
	{ next.push(null); }

	const gives = [...(giveLines ?? [])]
		.map((line) => ({
			bagSlotIndex: line.bagSlotIndex | 0,
			quantity: Math.max(1, line.quantity | 0 || 1)
		}))
		.sort((a, b) => b.bagSlotIndex - a.bagSlotIndex);

	for (const line of gives)
	{
		const taken = takeFromSlot(next, line.bagSlotIndex, line.quantity);
		if (!taken.ok)
		{ return INVENTORY_SLOTS; }
		next = taken.slots;
	}

	for (const stack of receiveStacks ?? [])
	{
		if (!stack)
		{ continue; }
		const def = itemDefinition(stack.itemId);
		if (!def)
		{ return INVENTORY_SLOTS; }
		const inserted = insertStack(next, cloneStack(stack), def);
		if (!inserted.ok || (inserted.remainder | 0) > 0)
		{
			const empty = next.filter((slot) => !slot).length;
			const needApprox = Math.max(1, Math.ceil(
				stackQuantity(stack.quantity) / Math.max(1, def.maxStackSize | 0 || 1)
			));
			return Math.max(1, needApprox - empty);
		}
		next = inserted.slots;
	}
	return 0;
}

/**
 * Snapshot offer lines as transferable stacks from a bag (or null if invalid).
 * Origins are sliced to the offered quantity (same as takeFromSlot).
 */
export function resolveOfferStacks (inventorySlots, offerLines)
{
	const stacks = [];
	for (const line of offerLines ?? [])
	{
		const slot = inventorySlots?.[line.bagSlotIndex | 0];
		const qty = Math.max(1, line.quantity | 0 || 1);
		if (!slot || stackQuantity(slot.quantity) < qty)
		{ return null; }
		const split = splitOrigins(normalizeOrigins(slot), qty);
		stacks.push(attachOrigins({
			itemId: slot.itemId,
			quantity: qty,
			instance: slot.instance ? structuredClone(slot.instance) : null,
			origins: split.taken
		}));
	}
	return stacks;
}
