import test from "node:test";
import assert from "node:assert/strict";
import { BlockType } from "../../shared/definitions/tiles.js";
import { ItemId } from "../../shared/definitions/items.js";
import { HerbId } from "../../shared/definitions/herbs.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
import { evaluateAlchemyBottle, resolvedAlchemyPotions } from "../../shared/alchemy/recipes.js";
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
import { totalXpForLevel } from "../../shared/skills/progression.js";
import { Component } from "../src/ecs/components.js";
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";

function placeBlock (worldDb, tileX, tileY, typeId, state = 0)
{
	const chunkX = Math.floor(tileX / 16);
	const chunkY = Math.floor(tileY / 16);
	const data = createEmptyChunkData();
	data.open = true;
	const localX = tileX - chunkX * 16;
	const localY = tileY - chunkY * 16;
	data.blocks[localY * 16 + localX] = { typeId, state };
	worldDb.saveChunkVersion(
		chunkX,
		chunkY,
		worldDb.getActiveRevisionId(),
		true,
		encodeChunkBlob(data)
	);
}

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

test("sage herb plant yields sage with matching-tier clippers", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.sage);
		harness.simulation.reloadWorld();
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
		const entityId = harness.simulation.spawnCharacter(1, character);
		const bag = harness.simulation.bagOf(entityId);
		bag.inventory = emptySlots();
		bag.inventory[0] = { itemId: ItemId.ironPlantClippers, quantity: 1 };
		bag.equipment = emptyEquipment();
		harness.simulation.applyBag(entityId, bag);

		const record = harness.simulation.entityRecord(entityId);
		const worker = harness.simulation.workers[record.workerId];
		const handle = worker.world.ecs.handleOf(entityId);
		const skills = worker.world.ecs.get(handle, Component.skills);
		/** Iron clippers need herbalism 10 to equip (sage gather gate is only 5). */
		skills.xp[SkillId.herbalism] = totalXpForLevel(10);

		harness.simulation.enqueue(1, {
			type: "pick",
			characterId: character.character_id,
			tileX: 8,
			tileY: 8
		});
		harness.simulation.step();
		harness.advance(4000);
		harness.simulation.step();
		assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.sage), 1);
	}
	finally
	{ harness.close(); }
});

test("sage herb plant rejects under-tier clippers", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.sage);
		harness.simulation.reloadWorld();
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
		const entityId = harness.simulation.spawnCharacter(1, character);
		const bag = harness.simulation.bagOf(entityId);
		bag.inventory = emptySlots();
		bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 };
		bag.equipment = emptyEquipment();
		harness.simulation.applyBag(entityId, bag);

		const record = harness.simulation.entityRecord(entityId);
		const worker = harness.simulation.workers[record.workerId];
		const handle = worker.world.ecs.handleOf(entityId);
		const skills = worker.world.ecs.get(handle, Component.skills);
		skills.xp[SkillId.herbalism] = totalXpForLevel(10);

		harness.simulation.enqueue(1, {
			type: "pick",
			characterId: character.character_id,
			tileX: 8,
			tileY: 8
		});
		const result = harness.simulation.step();
		const error = result.events.find((event) => event.type === "command-error");
		assert.ok(error);
		assert.match(error.message, /Iron plant clippers/i);
	}
	finally
	{ harness.close(); }
});

test("aconite herb plant rejects low herbalism", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.aconite);
		harness.simulation.reloadWorld();
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
		const entityId = harness.simulation.spawnCharacter(1, character);
		const bag = harness.simulation.bagOf(entityId);
		bag.inventory = emptySlots();
		bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 };
		bag.equipment = emptyEquipment();
		harness.simulation.applyBag(entityId, bag);

		harness.simulation.enqueue(1, {
			type: "pick",
			characterId: character.character_id,
			tileX: 8,
			tileY: 8
		});
		const result = harness.simulation.step();
		const error = result.events.find((event) => event.type === "command-error");
		assert.ok(error);
		assert.match(error.message, /Herbalism 45/i);
	}
	finally
	{ harness.close(); }
});

test("starter potions evaluate with herb recipes", () =>
{
	const tonic = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic");
	assert.ok(tonic);
	const evaluation = evaluateAlchemyBottle({
		skills: { levels: { alchemy: 1 } },
		brewStacks: [
			{ itemId: ItemId.thyme, quantity: 1 },
			{ itemId: ItemId.mint, quantity: 1 }
		],
		takenSteps: [
			{ kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
			{ kind: AlchemyStepKind.heat },
			{ kind: AlchemyStepKind.insert, itemId: ItemId.mint },
			{ kind: AlchemyStepKind.stir }
		]
	});
	assert.equal(evaluation.success, true);
	assert.equal(evaluation.result.potionKey, "lesserHealthTonic");
	assert.equal(evaluation.result.effect.type, "health-regen");

	const strength = evaluateAlchemyBottle({
		skills: { levels: { alchemy: 1 } },
		brewStacks: [
			{ itemId: ItemId.thyme, quantity: 3 },
			{ itemId: ItemId.nettle, quantity: 2 }
		],
		takenSteps: [
			{ kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
			{ kind: AlchemyStepKind.stir },
			{ kind: AlchemyStepKind.insert, itemId: ItemId.nettle },
			{ kind: AlchemyStepKind.heat }
		]
	});
	assert.equal(strength.success, true);
	assert.equal(strength.result.potionKey, "strengthPotion");
});
