/**
 * Pure doorway-portal graph for courier cross-dimension routing.
 * Edges are unidirectional (from doorway tile → configured target).
 */

import { OVERWORLD_ID, normalizeDimensionId } from "../world/dimensions.js";
import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";

/**
 * @typedef {{
 *   fromDimensionId: string,
 *   fromTileX: number,
 *   fromTileY: number,
 *   toDimensionId: string,
 *   toTileX: number,
 *   toTileY: number
 * }} DoorwayEdge
 */

/**
 * @typedef {{
 *   kind: "fly" | "portal" | "abstract",
 *   fromDimensionId?: string,
 *   fromX?: number,
 *   fromY?: number,
 *   toDimensionId?: string,
 *   toX?: number,
 *   toY?: number,
 *   distance?: number
 * }} CourierLeg
 */

/**
 * Build a directed doorway graph from scanned doorway tiles.
 * @param {Array<{
 *   tileX: number,
 *   tileY: number,
 *   dimensionId?: string,
 *   targetDimensionId?: string,
 *   targetTileX?: number,
 *   targetTileY?: number
 * }>} doorways
 */
export function buildDoorwayGraph (doorways)
{
	const edges = [];
	/** @type {Map<string, DoorwayEdge[]>} */
	const byFromDim = new Map();
	for (const doorway of doorways ?? [])
	{
		const targetRaw = doorway?.targetDimensionId;
		if (targetRaw == null || String(targetRaw).trim() === "")
		{ continue; }
		const targetTileX = Number(doorway.targetTileX);
		const targetTileY = Number(doorway.targetTileY);
		if (!Number.isFinite(targetTileX) || !Number.isFinite(targetTileY))
		{ continue; }
		/** @type {DoorwayEdge} */
		const edge = {
			fromDimensionId: normalizeDimensionId(doorway.dimensionId ?? OVERWORLD_ID),
			fromTileX: doorway.tileX | 0,
			fromTileY: doorway.tileY | 0,
			toDimensionId: normalizeDimensionId(targetRaw),
			toTileX: targetTileX | 0,
			toTileY: targetTileY | 0
		};
		edges.push(edge);
		const list = byFromDim.get(edge.fromDimensionId);
		if (list)
		{ list.push(edge); }
		else
		{ byFromDim.set(edge.fromDimensionId, [edge]); }
	}
	return { edges, byFromDim };
}

/**
 * BFS over dimensions via doorway edges. Returns the doorway edge sequence,
 * or null if unreachable. Same-dimension yields [].
 * @param {{ byFromDim: Map<string, DoorwayEdge[]> }} graph
 * @param {string} fromDimensionId
 * @param {string} toDimensionId
 * @returns {DoorwayEdge[] | null}
 */
export function findDimensionPath (graph, fromDimensionId, toDimensionId)
{
	const fromDim = normalizeDimensionId(fromDimensionId);
	const toDim = normalizeDimensionId(toDimensionId);
	if (fromDim === toDim)
	{ return []; }
	const byFromDim = graph?.byFromDim ?? new Map();
	const queue = [fromDim];
	const visited = new Set([fromDim]);
	/** @type {Map<string, DoorwayEdge>} */
	const cameVia = new Map();
	let head = 0;
	while (head < queue.length)
	{
		const current = queue[head++];
		for (const edge of byFromDim.get(current) ?? [])
		{
			const next = edge.toDimensionId;
			if (visited.has(next))
			{ continue; }
			visited.add(next);
			cameVia.set(next, edge);
			if (next === toDim)
			{
				const path = [];
				let dim = toDim;
				while (dim !== fromDim)
				{
					const via = cameVia.get(dim);
					if (!via)
					{ return null; }
					path.push(via);
					dim = via.fromDimensionId;
				}
				path.reverse();
				return path;
			}
			queue.push(next);
		}
	}
	return null;
}

function flyLeg (fromDimensionId, fromX, fromY, toDimensionId, toX, toY)
{
	return {
		kind: "fly",
		fromDimensionId: normalizeDimensionId(fromDimensionId),
		fromX,
		fromY,
		toDimensionId: normalizeDimensionId(toDimensionId),
		toX,
		toY
	};
}

function portalLeg (edge)
{
	return {
		kind: "portal",
		fromDimensionId: edge.fromDimensionId,
		fromX: edge.fromTileX + 0.5,
		fromY: edge.fromTileY + 0.5,
		toDimensionId: edge.toDimensionId,
		toX: edge.toTileX + 0.5,
		toY: edge.toTileY + 0.5
	};
}

/**
 * Plan courier legs from origin to destination using the doorway graph.
 * Same-dim → single fly. Cross-dim with path → fly/portal/fly….
 * Cross-dim with no path → { mode: "fallback", legs: null } (caller builds fade legs).
 */
export function planPortalLegs ({
	fromX,
	fromY,
	fromDimensionId = OVERWORLD_ID,
	toX,
	toY,
	toDimensionId = OVERWORLD_ID,
	graph
})
{
	const fromDim = normalizeDimensionId(fromDimensionId);
	const toDim = normalizeDimensionId(toDimensionId);
	if (fromDim === toDim)
	{
		return {
			mode: "direct",
			legs: [flyLeg(fromDim, fromX, fromY, toDim, toX, toY)]
		};
	}
	const doorPath = findDimensionPath(graph, fromDim, toDim);
	if (!doorPath)
	{
		return { mode: "fallback", legs: null };
	}
	/** @type {CourierLeg[]} */
	const legs = [];
	let cx = fromX;
	let cy = fromY;
	let cd = fromDim;
	for (const edge of doorPath)
	{
		const enterX = edge.fromTileX + 0.5;
		const enterY = edge.fromTileY + 0.5;
		legs.push(flyLeg(cd, cx, cy, cd, enterX, enterY));
		legs.push(portalLeg(edge));
		cx = edge.toTileX + 0.5;
		cy = edge.toTileY + 0.5;
		cd = edge.toDimensionId;
	}
	legs.push(flyLeg(cd, cx, cy, toDim, toX, toY));
	return { mode: "portal", legs };
}

/**
 * Walk from (x,y) along unit direction until `stop(tileX, tileY)` is true.
 * Returns the first tile-center where stop is true, or the last sample if never.
 */
export function walkUntilStop ({
	x,
	y,
	dirX,
	dirY,
	stop,
	maxSteps = 96,
	step = 1
})
{
	let px = x;
	let py = y;
	const len = Math.hypot(dirX, dirY);
	const ux = len > 1e-9 ? dirX / len : 1;
	const uy = len > 1e-9 ? dirY / len : 0;
	for (let i = 0; i < maxSteps; i++)
	{
		px += ux * step;
		py += uy * step;
		if (stop(Math.floor(px), Math.floor(py)))
		{ return { x: px, y: py, steps: i + 1 }; }
	}
	return { x: px, y: py, steps: maxSteps };
}

export function estimateAbstractDistance ({
	fromX,
	fromY,
	toX,
	toY,
	fadeOutDist = 0,
	fadeInDist = 0,
	crossDimension = false
})
{
	const direct = Math.hypot(toX - fromX, toY - fromY);
	const budget = crossDimension ? Math.max(direct, 32) : direct;
	return Math.max(0, budget - fadeOutDist - fadeInDist);
}

/**
 * Build fade-out → abstract → fade-in legs when no doorway path exists.
 * `isSimulating(tileX, tileY, dimensionId)` must not force-load regions.
 */
export function buildFallbackLegs ({
	fromX,
	fromY,
	fromDimensionId = OVERWORLD_ID,
	toX,
	toY,
	toDimensionId = OVERWORLD_ID,
	isSimulating,
	settings = DEFAULT_WORLD_SETTINGS
})
{
	void settings;
	const fromDim = normalizeDimensionId(fromDimensionId);
	const toDim = normalizeDimensionId(toDimensionId);
	const awayX = fromX - toX;
	const awayY = fromY - toY;
	const awayLen = Math.hypot(awayX, awayY);
	const outDirX = awayLen > 1e-9 ? awayX / awayLen : 1;
	const outDirY = awayLen > 1e-9 ? awayY / awayLen : 0;

	/** @type {CourierLeg[]} */
	const legs = [];
	let fadeOutEndX = fromX;
	let fadeOutEndY = fromY;
	let fadeOutDist = 0;
	if (typeof isSimulating === "function"
		&& isSimulating(Math.floor(fromX), Math.floor(fromY), fromDim))
	{
		const exit = walkUntilStop({
			x: fromX,
			y: fromY,
			dirX: outDirX,
			dirY: outDirY,
			stop: (tx, ty) => !isSimulating(tx, ty, fromDim)
		});
		fadeOutEndX = exit.x;
		fadeOutEndY = exit.y;
		fadeOutDist = Math.hypot(fadeOutEndX - fromX, fadeOutEndY - fromY);
		legs.push(flyLeg(fromDim, fromX, fromY, fromDim, fadeOutEndX, fadeOutEndY));
	}

	const approachX = toX - fromX;
	const approachY = toY - fromY;
	const approachLen = Math.hypot(approachX, approachY);
	const backDirX = approachLen > 1e-9 ? -approachX / approachLen : -1;
	const backDirY = approachLen > 1e-9 ? -approachY / approachLen : 0;

	let fadeInStartX = toX;
	let fadeInStartY = toY;
	let fadeInDist = 0;
	const destSimulating = typeof isSimulating === "function"
		&& isSimulating(Math.floor(toX), Math.floor(toY), toDim);
	if (destSimulating)
	{
		const entry = walkUntilStop({
			x: toX,
			y: toY,
			dirX: backDirX,
			dirY: backDirY,
			stop: (tx, ty) => !isSimulating(tx, ty, toDim)
		});
		fadeInStartX = entry.x;
		fadeInStartY = entry.y;
		fadeInDist = Math.hypot(toX - fadeInStartX, toY - fadeInStartY);
	}

	const abstractDistance = estimateAbstractDistance({
		fromX,
		fromY,
		toX,
		toY,
		fadeOutDist,
		fadeInDist,
		crossDimension: fromDim !== toDim
	});
	legs.push({
		kind: "abstract",
		fromDimensionId: fromDim,
		fromX: fadeOutEndX,
		fromY: fadeOutEndY,
		toDimensionId: toDim,
		toX: fadeInStartX,
		toY: fadeInStartY,
		distance: abstractDistance
	});
	legs.push(flyLeg(toDim, fadeInStartX, fadeInStartY, toDim, toX, toY));
	return { mode: "fallback", legs };
}

/**
 * Advance an abstract (invisible) travel leg at cruise speed.
 */
export function advanceAbstractTravel ({
	traveled,
	distance,
	dt,
	settings = DEFAULT_WORLD_SETTINGS
})
{
	const total = Math.max(0, distance ?? 0);
	const cruise = Math.max(0.25, settings.pigeonCruiseTilesPerSec ?? 8);
	if (!(total > 0))
	{
		return {
			traveled: 0,
			arrived: true,
			speed: 0,
			total: 0
		};
	}
	const nextTraveled = Math.min(total, (traveled || 0) + cruise * Math.max(0, dt));
	return {
		traveled: nextTraveled,
		arrived: nextTraveled >= total - 1e-6,
		speed: cruise,
		total
	};
}

/**
 * Pose along the current leg given traveled distance.
 * Abstract legs have no visible pose (returns null).
 */
export function poseOnCourierLeg (leg, traveled = 0)
{
	if (!leg)
	{ return null; }
	if (leg.kind === "abstract")
	{ return null; }
	if (leg.kind === "portal")
	{
		return {
			x: leg.toX,
			y: leg.toY,
			dimensionId: normalizeDimensionId(leg.toDimensionId ?? OVERWORLD_ID)
		};
	}
	const fromX = leg.fromX;
	const fromY = leg.fromY;
	const toX = leg.toX;
	const toY = leg.toY;
	const total = Math.hypot(toX - fromX, toY - fromY);
	const t = total < 1e-6 ? 1 : Math.min(1, Math.max(0, (traveled || 0) / total));
	return {
		x: fromX + (toX - fromX) * t,
		y: fromY + (toY - fromY) * t,
		dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
	};
}

/**
 * Normalize / migrate a transit's legs. Old rows without legs become a single fly.
 */
export function ensureCourierLegs (transit)
{
	if (Array.isArray(transit.legs) && transit.legs.length > 0)
	{
		transit.legIndex = Math.max(0, Math.min(transit.legIndex | 0, transit.legs.length - 1));
		return transit;
	}
	const fromDim = normalizeDimensionId(transit.originDimensionId ?? OVERWORLD_ID);
	const toDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
	transit.legs = [flyLeg(
		fromDim,
		transit.originX,
		transit.originY,
		toDim,
		transit.destX,
		transit.destY
	)];
	transit.legIndex = 0;
	transit.originDimensionId = fromDim;
	transit.destDimensionId = toDim;
	return transit;
}
