import { Component } from "../ecs/components.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
import { 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 { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
import { smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
import { bagView } from "../items/bags.js";
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";

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

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

function nearStationBlock (world, tileX, tileY, blockType)
{
	for (let dy = -1; dy <= 1; dy++)
	{
		for (let dx = -1; dx <= 1; dx++)
		{
			const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
			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; }
	return null;
}

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 };
}

export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
{
	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 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 blockType = stationBlockType(stationId);
	if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
	{ 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);
	if (!canStartCraft(inventory?.slots ?? [], recipe, level))
	{
		if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
		{ throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
		if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
		{ throw userError("Missing materials."); }
		throw userError("Not enough bag space for the result.");
	}

	const sessions = ensureCraftSessions(world);
	sessions.set(characterId, {
		sessionId,
		stationId,
		recipeId,
		finishesAt: now + CRAFT_DURATION_MS
	});
	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)
	});
	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);
	if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
	{ 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 = 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 blockType = stationBlockType(session.stationId);
		const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);

		if (!recipe || !stationDef || !inventory
			|| (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
			|| !canCraftFitInventory(inventory.slots, recipe)
			|| (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;
		}
		const outDef = itemDefinition(recipe.output.itemId);
		const added = insertStack(taken.slots, {
			itemId: recipe.output.itemId,
			quantity: Math.max(1, recipe.output.quantity | 0 || 1)
		}, 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;
		if (skills?.xp && recipe.xpMaterial && stationDef.skillId === SkillId.smithing)
		{
			if (addSkillXp(skills, SkillId.smithing, smeltingXpForMaterial(recipe.xpMaterial)))
			{ skillsChanged = true; }
		}

		privates.push({ characterId, bag: bagView(world.ecs, handle) });
		if (skillsChanged)
		{
			events.push({
				type: "skills-updated",
				characterId,
				skills: publicSkillsView(skills),
				stored: storedSkillXp(skills)
			});
		}
		events.push({
			type: "craft-result",
			sessionId: session.sessionId,
			recipeId: session.recipeId,
			ok: true
		});
	}
	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
			);
		case "cancel-craft":
			return cancelCraft(world, command.characterId);
		default:
			return null;
	}
}
