import { Component } from "../ecs/components.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_CHANCE_CAMPFIRE } from "../../../shared/definitions/craftingStations.js";
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
import
{
	recipeDefinition,
	canStartCraft,
	canCraftFitInventory,
	hasRecipeInputs
} from "../../../shared/crafting/recipes.js";
import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
import { pickEmptiestDyeSlot } from "../../../shared/crafting/dye.js";
import { pickEmptiestPotionSlot } from "../../../shared/crafting/potionCharge.js";
import { dyeColorKey as dyeInstanceColorKey } from "../../../shared/definitions/dyes.js";
import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
import
{
	attachOrigins,
	craftOrigin,
	craftOriginVerbForStation,
	CraftOriginVerb
} from "../../../shared/items/origin.js";
import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
import { craftDurationMultiplier } from "../../../shared/equipment/jewelryEffects.js";
import { bagView } from "../items/bags.js";
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";

function userError (message)
{
	const error = new Error(message);
	error.userFacing = true;
	return error;
}

function characterDisplayName (world, handle)
{
	const appearance = world.ecs.get(handle, Component.appearance);
	const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
	return name || "someone";
}

function ensureCraftSessions (world)
{
	if (!world.craftSessions)
	{ world.craftSessions = new Map(); }
	return world.craftSessions;
}

function nearStationBlock (world, tileX, tileY, blockType, dimensionId = OVERWORLD_ID)
{
	const dim = normalizeDimensionId(dimensionId);
	for (let dy = -1; dy <= 1; dy++)
	{
		for (let dx = -1; dx <= 1; dx++)
		{
			if (dx === 0 && dy === 0)
			{ continue; }
			const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim);
			const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
			if (data.blocks[index]?.typeId === blockType)
			{ return true; }
		}
	}
	return false;
}

function stationBlockType (stationId)
{
	if (stationId === CraftingStationId.furnace)
	{ return BlockType.furnace; }
	if (stationId === CraftingStationId.anvil)
	{ return BlockType.anvil; }
	if (stationId === CraftingStationId.jeweleringStation)
	{ return BlockType.jeweleringStation; }
	if (stationId === CraftingStationId.woodworkingBench)
	{ return BlockType.woodworkingBench; }
	if (stationId === CraftingStationId.craftingBench)
	{ return BlockType.craftingBench; }
	if (stationId === CraftingStationId.spinningWheel)
	{ return BlockType.spinningWheel; }
	if (stationId === CraftingStationId.loom)
	{ return BlockType.loom; }
	if (stationId === CraftingStationId.tailorBench)
	{ return BlockType.tailorBench; }
	if (stationId === CraftingStationId.leatherworkingStation)
	{ return BlockType.leatherworkingTable; }
	if (stationId === CraftingStationId.oven)
	{ return BlockType.oven; }
	if (stationId === CraftingStationId.fireplace)
	{ return BlockType.campfire; }
	return null;
}

function cookBurnChance (stationId)
{
	if (stationId === CraftingStationId.fireplace)
	{ return COOK_BURN_CHANCE_CAMPFIRE; }
	if (stationId === CraftingStationId.oven)
	{ return COOK_BURN_CHANCE_OVEN; }
	return 0;
}

function takeInputs (slots, inputs)
{
	let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
	for (const input of inputs ?? [])
	{
		let remaining = Math.max(0, stackQuantity(input.quantity));
		if (!remaining)
		{ continue; }
		for (let i = 0; i < next.length && remaining > 0; i++)
		{
			if (!next[i] || next[i].itemId !== input.itemId)
			{ continue; }
			const taken = takeFromSlot(next, i, remaining);
			if (!taken.ok)
			{ continue; }
			next = taken.slots;
			remaining -= stackQuantity(taken.taken?.quantity);
		}
		if (remaining > 0)
		{ return { ok: false, slots }; }
	}
	return { ok: true, slots: next };
}

/** Spend one fill level of a dye bottle (remove at 0). Never loses the leftover. */
function consumeDyeUse (slots, slotIndex)
{
	return consumeFillCharge(slots, slotIndex, {
		kind: "dye",
		itemId: ItemId.dye
	});
}

/** Spend one fill of a potion bottle; exhausted bottles become empty glass. */
function consumePotionUse (slots, slotIndex)
{
	return consumeFillCharge(slots, slotIndex, {
		kind: "potion",
		itemId: ItemId.potion,
		returnEmptyItemId: ItemId.glassBottle
	});
}

export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
{
	const entityId = world.characterEntities.get(characterId);
	if (entityId == null)
	{ throw userError("Character is not in the world."); }
	const handle = world.ecs.handleOf(entityId);
	const identity = world.ecs.get(handle, Component.networkIdentity);
	if (!identity || identity.sessionId !== sessionId)
	{ throw userError("Character is not in the world."); }
	if (world.ecs.has(handle, Component.dead))
	{ throw userError("You are dead."); }

	const stationDef = craftingStationDefinition(stationId);
	if (!stationDef)
	{ throw userError("Unknown crafting station."); }
	let recipe = recipeDefinition(recipeId);
	if (!recipe)
	{ throw userError("Unknown recipe."); }
	const stationIds = Array.isArray(recipe.stationIds)
		? recipe.stationIds
		: [recipe.stationId];
	if (!stationIds.includes(stationId))
	{ throw userError("That recipe cannot be made here."); }

	const position = world.ecs.get(handle, Component.position);
	const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
	const blockType = stationBlockType(stationId);
	if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
	{ throw userError("You need to stand next to the station."); }

	const inventory = world.ecs.get(handle, Component.inventory);
	const skills = world.ecs.get(handle, Component.skills);
	const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);

	let dyeColorKey = null;
	if (recipe.tailorTemplate)
	{
		if (stationId !== CraftingStationId.tailorBench)
		{ throw userError("That garment can only be made at a tailor's bench."); }
		const dyeIdx = options.dyeSlotIndex;
		let dyeStack = null;
		if (dyeIdx != null && dyeIdx >= 0)
		{
			dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null;
			dyeColorKey = dyeStack ? dyeInstanceColorKey(dyeStack.instance) : null;
		}
		const resolved = resolveTailorCraft({
			templateId: recipe.tailorTemplate,
			clothTier: options.clothTier,
			dyeStack
		});
		if (!resolved.ok)
		{ throw userError(resolved.reason); }
		recipe = resolved.recipe;
	}
	else if (options.dyeSlotIndex != null)
	{
		// Dye is tailor-only; ignore client-supplied dye on other stations.
		dyeColorKey = null;
	}

	if (!canStartCraft(inventory?.slots ?? [], recipe, level, { dyeColorKey, dyeSlotIndex: options.dyeSlotIndex ?? null }))
	{
		if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
		{ throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
		if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
		{ throw userError("Missing materials."); }
		if (recipe.consumeDye && dyeColorKey != null)
		{
			const probeSlot = pickEmptiestDyeSlot(inventory?.slots ?? [], dyeColorKey);
			const dyeProbe = consumeDyeUse(inventory?.slots ?? [], probeSlot);
			if (!dyeProbe.ok)
			{ throw userError("Need bag space to separate the partially used dye."); }
		}
		if (recipe.consumePotionKey)
		{
			const probeSlot = pickEmptiestPotionSlot(inventory?.slots ?? [], recipe.consumePotionKey);
			const potionProbe = consumePotionUse(inventory?.slots ?? [], probeSlot);
			if (!potionProbe.ok)
			{ throw userError("Need bag space to separate the partially used brew."); }
		}
		throw userError("Not enough bag space for the result.");
	}
	if (recipe.consumeDye && dyeColorKey != null)
	{
		const probeSlot = pickEmptiestDyeSlot(inventory?.slots ?? [], dyeColorKey);
		const dye = inventory?.slots?.[probeSlot];
		if (!dye || dye.itemId !== ItemId.dye)
		{ throw userError("Selected dye is missing."); }
	}
	if (recipe.consumePotionKey)
	{
		const probeSlot = pickEmptiestPotionSlot(inventory?.slots ?? [], recipe.consumePotionKey);
		if (probeSlot == null)
		{ throw userError("Missing materials."); }
	}

	const sessions = ensureCraftSessions(world);
	const equipment = world.ecs.get(handle, Component.equipment);
	const durationMs = Math.max(
		1,
		Math.floor(craftDurationMs(recipe, CRAFT_DURATION_MS) * craftDurationMultiplier(equipment))
	);
	let batchRemaining = 1;
	if (options.batchAll)
	{ batchRemaining = Infinity; }
	else if (options.batchCount != null)
	{ batchRemaining = Math.max(1, options.batchCount | 0); }
	sessions.set(characterId, {
		sessionId,
		stationId,
		recipeId,
		recipe,
		dyeColorKey,
		batchRemaining,
		durationMs,
		finishesAt: now + durationMs
	});
	const events = [];
	if (blockType)
	{
		const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
		if (shove)
		{ events.push(shove); }
	}
	events.push({
		type: "item-bubble",
		entityId,
		itemId: recipe.output.itemId,
		quantity: Math.max(1, recipe.output.quantity | 0 || 1)
	});
	events.push({
		type: "craft-started",
		sessionId,
		characterId,
		recipeId,
		durationMs
	});
	return { events };
}

export function openStation (world, sessionId, characterId, stationId)
{
	const entityId = world.characterEntities.get(characterId);
	if (entityId == null)
	{ throw userError("Character is not in the world."); }
	const handle = world.ecs.handleOf(entityId);
	const identity = world.ecs.get(handle, Component.networkIdentity);
	if (!identity || identity.sessionId !== sessionId)
	{ throw userError("Character is not in the world."); }
	if (world.ecs.has(handle, Component.dead))
	{ throw userError("You are dead."); }

	const stationDef = craftingStationDefinition(stationId);
	if (!stationDef)
	{ throw userError("Unknown crafting station."); }
	const blockType = stationBlockType(stationId);
	const position = world.ecs.get(handle, Component.position);
	const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
	if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
	{ throw userError("You need to stand next to the station."); }

	const events = [];
	if (blockType)
	{
		const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
		if (shove)
		{ events.push(shove); }
	}
	events.push({
		type: "station-open",
		sessionId,
		characterId,
		stationId
	});
	return { events };
}

export function cancelCraft (world, characterId)
{
	ensureCraftSessions(world).delete(characterId);
	return { events: [] };
}

export function stepCrafting (world, now)
{
	const sessions = ensureCraftSessions(world);
	const events = [];
	const privates = [];
	for (const [characterId, session] of [...sessions.entries()])
	{
		if (now < session.finishesAt)
		{ continue; }
		sessions.delete(characterId);
		const entityId = world.characterEntities.get(characterId);
		if (entityId == null)
		{
			events.push({
				type: "craft-result",
				sessionId: session.sessionId,
				recipeId: session.recipeId,
				ok: false,
				error: "Character left the world."
			});
			continue;
		}
		const handle = world.ecs.handleOf(entityId);
		if (world.ecs.has(handle, Component.dead))
		{
			events.push({
				type: "craft-result",
				sessionId: session.sessionId,
				recipeId: session.recipeId,
				ok: false,
				error: "You are dead."
			});
			continue;
		}

		const recipe = session.recipe ?? recipeDefinition(session.recipeId);
		const stationDef = craftingStationDefinition(session.stationId);
		const inventory = world.ecs.get(handle, Component.inventory);
		const skills = world.ecs.get(handle, Component.skills);
		const position = world.ecs.get(handle, Component.position);
		const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
		const blockType = stationBlockType(session.stationId);
		const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);

		if (!recipe || !stationDef || !inventory
			|| (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
			|| !canCraftFitInventory(inventory.slots, recipe, { dyeColorKey: session.dyeColorKey })
			|| (level | 0) < (recipe.minSkillLevel | 0 || 1))
		{
			events.push({
				type: "craft-result",
				sessionId: session.sessionId,
				recipeId: session.recipeId,
				ok: false,
				error: "Could not finish crafting."
			});
			continue;
		}

		const taken = takeInputs(inventory.slots, recipe.inputs);
		if (!taken.ok)
		{
			events.push({
				type: "craft-result",
				sessionId: session.sessionId,
				recipeId: session.recipeId,
				ok: false,
				error: "Missing materials."
			});
			continue;
		}
		let slotsAfter = taken.slots;
		if (recipe.consumeDye && session.dyeColorKey != null)
		{
			const consumeSlot = pickEmptiestDyeSlot(slotsAfter, session.dyeColorKey);
			const dyeTaken = consumeDyeUse(slotsAfter, consumeSlot);
			if (!dyeTaken.ok)
			{
				events.push({
					type: "craft-result",
					sessionId: session.sessionId,
					recipeId: session.recipeId,
					ok: false,
					error: dyeTaken.reason === "space"
						? "Need bag space to separate the partially used dye."
						: "Selected dye is missing."
				});
				continue;
			}
			slotsAfter = dyeTaken.slots;
		}
		if (recipe.consumePotionKey)
		{
			const consumeSlot = pickEmptiestPotionSlot(slotsAfter, recipe.consumePotionKey);
			const potionTaken = consumePotionUse(slotsAfter, consumeSlot);
			if (!potionTaken.ok)
			{
				events.push({
					type: "craft-result",
					sessionId: session.sessionId,
					recipeId: session.recipeId,
					ok: false,
					error: potionTaken.reason === "space"
						? "Need bag space to separate the partially used brew."
						: "Missing materials."
				});
				continue;
			}
			slotsAfter = potionTaken.slots;
		}

		const burnChance = cookBurnChance(session.stationId);
		const burned = burnChance > 0
			&& recipe.burntOutput?.itemId
			&& ((world.rng?.() ?? Math.random()) < burnChance);
		const outSpec = burned ? recipe.burntOutput : recipe.output;
		const outDef = itemDefinition(outSpec.itemId);
		const outQty = Math.max(1, outSpec.quantity | 0 || 1);
		const origin = craftOrigin(
			burned ? CraftOriginVerb.ruined : craftOriginVerbForStation(session.stationId),
			characterDisplayName(world, handle)
		);
		const outStack = {
			itemId: outSpec.itemId,
			quantity: outQty,
			origins: [{ origin, quantity: outQty }],
			...(recipe.dyeColor && !burned ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
		};
		const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
		if (!added.ok || added.remainder > 0)
		{
			events.push({
				type: "craft-result",
				sessionId: session.sessionId,
				recipeId: session.recipeId,
				ok: false,
				error: "Not enough bag space for the result."
			});
			continue;
		}
		inventory.slots = added.slots;

		let skillsChanged = false;
		const levelUps = [];
		if (!burned && skills?.xp && stationDef?.skillId)
		{
			const result = applySkillXp(
				skills,
				stationDef.skillId,
				craftXpForConsumedInputs(recipe.inputs, stationDef.skillId),
				world.ecs.get(handle, Component.equipment)
			);
			if (result.changed)
			{ skillsChanged = true; }
			if (result.levelUp)
			{ levelUps.push(result.levelUp); }
		}

		privates.push({ characterId, bag: bagView(world.ecs, handle) });
		if (skillsChanged)
		{
			events.push({
				type: "skills-updated",
				entityId,
				characterId,
				...publicSkillsPayload(skills),
				stored: storedSkillXp(skills),
				levelUps
			});
		}

		if (burned)
		{
			events.push({
				type: "command-error",
				sessionId: session.sessionId,
				message: "You burn the food."
			});
		}

		let continuing = false;
		const batchRemaining = session.batchRemaining ?? 1;
		const nextRemaining = batchRemaining === Infinity
			? Infinity
			: Math.max(0, (batchRemaining | 0) - 1);
		if (nextRemaining !== 0 && canStartCraft(
			inventory.slots,
			recipe,
			level,
			{ dyeColorKey: session.dyeColorKey, dyeSlotIndex: null }
		))
		{
			const equipment = world.ecs.get(handle, Component.equipment);
			const durationMs = session.durationMs ?? Math.max(
				1,
				Math.floor(craftDurationMs(recipe, CRAFT_DURATION_MS) * craftDurationMultiplier(equipment))
			);
			sessions.set(characterId, {
				...session,
				recipe,
				batchRemaining: nextRemaining,
				durationMs,
				finishesAt: now + durationMs
			});
			continuing = true;
			if (blockType)
			{
				const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
				if (shove)
				{ events.push(shove); }
			}
			events.push({
				type: "item-bubble",
				entityId,
				itemId: outSpec.itemId,
				quantity: outQty
			});
			events.push({
				type: "craft-started",
				sessionId: session.sessionId,
				characterId,
				recipeId: session.recipeId,
				durationMs
			});
		}
		events.push({
			type: "craft-result",
			sessionId: session.sessionId,
			recipeId: session.recipeId,
			ok: true,
			continuing
		});
	}
	return { events, privates };
}

export function handleCraftCommand (world, sessionId, command, now)
{
	switch (command.type)
	{
		case "open-station":
			return openStation(world, sessionId, command.characterId, command.stationId);
		case "start-craft":
			return startCraft(
				world,
				sessionId,
				command.characterId,
				command.stationId,
				command.recipeId,
				now,
				{
					clothTier: command.clothTier ?? null,
					dyeSlotIndex: command.dyeSlotIndex ?? null,
					batchCount: command.batchCount ?? null,
					batchAll: !!command.batchAll
				}
			);
		case "cancel-craft":
			return cancelCraft(world, command.characterId);
		default:
			return null;
	}
}
