import test from "node:test";
import assert from "node:assert/strict";
import { BlockType } from "../../shared/definitions/tiles.js";
import {
	CraftingStationId,
	firestartingDifficulty,
	campfireDurationMs,
	COOK_BURN_CHANCE_OVEN,
	COOK_BURN_CHANCE_CAMPFIRE,
	CRAFT_DURATION_MS
} from "../../shared/definitions/craftingStations.js";
import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
import { WoodItemId, ashItemIdForWood } from "../../shared/definitions/woodItems.js";
import { WoodTier } from "../../shared/definitions/materialTiers.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { recipeDefinition } from "../../shared/crafting/stationRecipes.js";
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
import { totalXpForLevel } from "../../shared/skills/progression.js";
import { ashTintColor } from "../../shared/render/tint.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
import { Component } from "../src/ecs/components.js";
import { addGroundItem } from "../src/items/bags.js";
import { StatusEffectType } from "../../shared/statusEffects/rules.js";

function countItem (slots, itemId)
{
	return (slots ?? []).reduce((sum, slot) =>
	{
		if (slot?.itemId === itemId)
		{ return sum + (slot.quantity | 0); }
		return sum;
	}, 0);
}

function workerOf (simulation, playerId)
{
	const record = simulation.entityRecord(playerId);
	return simulation.workers[record.workerId];
}

function setSkillLevel (worker, playerId, skillId, level)
{
	const handle = worker.world.ecs.handleOf(playerId);
	const skills = worker.world.ecs.get(handle, Component.skills);
	skills.xp[skillId] = totalXpForLevel(level);
}

function giveInventory (harness, playerId, items)
{
	const inventory = emptySlots();
	items.forEach((stack, index) =>
	{
		inventory[index] = {
			itemId: stack.itemId,
			quantity: stack.quantity,
			...(stack.instance ? { instance: structuredClone(stack.instance) } : {})
		};
	});
	harness.simulation.applyBag(playerId, {
		inventory,
		equipment: emptyEquipment(),
		vault: [],
		vaultReserved: []
	});
}

function advanceMs (harness, ms)
{
	const ticks = Math.ceil(ms / 50) + 3;
	for (let i = 0; i < ticks; i++)
	{
		harness.advance(50);
		harness.simulation.step();
	}
}

function placeStation (worker, tileX, tileY, typeId, state)
{
	const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
	const localX = ((tileX % 16) + 16) % 16;
	const localY = ((tileY % 16) + 16) % 16;
	data.blocks[localY * 16 + localX] = {
		typeId,
		state,
		config: null
	};
}

test("firestarting difficulty and campfire duration scale with wood tier", () =>
{
	assert.equal(firestartingDifficulty(WoodTier.pine), 1);
	assert.equal(firestartingDifficulty(WoodTier.birch), 10);
	assert.equal(firestartingDifficulty(WoodTier.oak), 20);
	assert.equal(campfireDurationMs(WoodTier.pine), 3 * 60_000);
	assert.equal(campfireDurationMs(WoodTier.oak), 9 * 60_000);
	assert.equal(COOK_BURN_CHANCE_OVEN, 0.1);
	assert.equal(COOK_BURN_CHANCE_CAMPFIRE, 0.35);
});

test("ash tint sits between dark grey and wood colour", () =>
{
	const tint = ashTintColor(WoodTier.pine);
	assert.ok(tint.r > 0.12 && tint.r < 0.9);
});

test("cook-venison recipe exists for oven and campfire with burnt output", () =>
{
	const recipe = recipeDefinition("cook-venison");
	assert.ok(recipe);
	assert.deepEqual(recipe.stationIds, [CraftingStationId.oven, CraftingStationId.fireplace]);
	assert.equal(recipe.output.itemId, CraftingItemId.cookedMeat);
	assert.equal(recipe.burntOutput.itemId, CraftingItemId.burntMeat);
	assert.equal(recipe.inputs[0].itemId, CraftingItemId.rawMeat);
});

test("start-fire places campfire and expiry drops ash", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const worker = workerOf(harness.simulation, playerId);
		worker.world.rng = () => 0.999;
		setSkillLevel(worker, playerId, SkillId.firestarting, 1);
		giveInventory(harness, playerId, [
			{ itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(20) }
		]);

		const groundItemId = 9001;
		addGroundItem(worker.world, {
			groundItemId,
			tileX: 9,
			tileY: 8,
			stack: { itemId: WoodItemId.pineLog, quantity: 1 },
			droppedAt: harness.now(),
			expiresAt: harness.now() + 600_000,
			source: "test"
		});

		harness.simulation.enqueue(1, {
			type: "start-fire",
			characterId: character.character_id,
			groundItemId
		});
		advanceMs(harness, 4000);

		const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
		assert.equal(block?.typeId, BlockType.campfire);
		assert.equal(block?.state, WoodTier.pine);
		assert.ok(worker.world.campfireExpires.has("9,8"));

		const bag = harness.simulation.bagOf(playerId);
		const tinder = bag.inventory.find((s) => s?.itemId === CraftingItemId.tinderbox);
		assert.equal(tinder?.instance?.charges, 19);

		const entry = worker.world.campfireExpires.get("9,8");
		entry.expiresAt = 0;
		advanceMs(harness, 200);
		assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
		const ashOnGround = [...worker.world.groundItems.values()].some(
			(item) => item.stack?.itemId === ashItemIdForWood(WoodTier.pine)
		);
		assert.equal(ashOnGround, true);
	}
	finally
	{ harness.close(); }
});

test("start-fire rejects too-low Firestarting for birch", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const worker = workerOf(harness.simulation, playerId);
		setSkillLevel(worker, playerId, SkillId.firestarting, 1);
		giveInventory(harness, playerId, [
			{ itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(5) }
		]);
		addGroundItem(worker.world, {
			groundItemId: 9002,
			tileX: 9,
			tileY: 8,
			stack: { itemId: WoodItemId.birchLog, quantity: 1 },
			droppedAt: harness.now(),
			expiresAt: harness.now() + 600_000,
			source: "test"
		});

		harness.simulation.enqueue(1, {
			type: "start-fire",
			characterId: character.character_id,
			groundItemId: 9002
		});
		advanceMs(harness, 200);
		assert.equal(worker.world.groundItems.has(9002), true);
		assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
	}
	finally
	{ harness.close(); }
});

test("oven cook can burn to burnt venison with seeded rng", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const worker = workerOf(harness.simulation, playerId);
		worker.world.rng = () => 0.01;
		setSkillLevel(worker, playerId, SkillId.cooking, 1);
		placeStation(worker, 9, 8, BlockType.oven, "oven");
		giveInventory(harness, playerId, [
			{ itemId: CraftingItemId.rawMeat, quantity: 1 }
		]);

		harness.simulation.enqueue(1, {
			type: "start-craft",
			characterId: character.character_id,
			stationId: CraftingStationId.oven,
			recipeId: "cook-venison"
		});
		advanceMs(harness, CRAFT_DURATION_MS + 500);

		const bag = harness.simulation.bagOf(playerId);
		assert.equal(countItem(bag.inventory, CraftingItemId.rawMeat), 0);
		assert.equal(countItem(bag.inventory, CraftingItemId.burntMeat), 1);
		assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 0);
	}
	finally
	{ harness.close(); }
});

test("oven cook succeeds when rng avoids burn", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const worker = workerOf(harness.simulation, playerId);
		worker.world.rng = () => 0.99;
		setSkillLevel(worker, playerId, SkillId.cooking, 1);
		placeStation(worker, 9, 8, BlockType.oven, "oven");
		giveInventory(harness, playerId, [
			{ itemId: CraftingItemId.rawMeat, quantity: 1 }
		]);

		harness.simulation.enqueue(1, {
			type: "start-craft",
			characterId: character.character_id,
			stationId: CraftingStationId.oven,
			recipeId: "cook-venison"
		});
		advanceMs(harness, CRAFT_DURATION_MS + 500);

		const bag = harness.simulation.bagOf(playerId);
		assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 1);
	}
	finally
	{ harness.close(); }
});

test("eating cooked venison heals and applies health regen", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		const health = worker.world.ecs.get(handle, Component.health);
		health.current = 5;
		health.max = 20;
		giveInventory(harness, playerId, [
			{ itemId: CraftingItemId.cookedMeat, quantity: 1 }
		]);

		harness.simulation.enqueue(1, {
			type: "eat-item",
			characterId: character.character_id,
			slotIndex: 0
		});
		harness.simulation.step();

		assert.equal(health.current, 10);
		const status = worker.world.ecs.get(handle, Component.statusEffects);
		const regen = status?.effects?.find((e) => e.type === StatusEffectType.healthRegen);
		assert.ok(regen);
		assert.equal(regen.amountPerSecond, 1);
	}
	finally
	{ harness.close(); }
});
