/**
 * Motion Mesh pipeline tools
 *
 * Registers three tools for the WoW-style skeletal-asset pipeline:
 *
 *   validate_rig       - structural validation of a glTF/GLB character
 *                        (skin/joints, bone naming, triangle & influence
 *                        budgets, height bounds, animation listing)
 *   export_gltf        - headless Blender glTF export via pipeline/blender_export.py
 *   check_bevy_import  - loads the asset with the real Bevy asset stack via
 *                        pipeline/bevy-check (cargo project), exit code drives pass/fail
 */

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type, type Static } from "typebox";
import { readFile } from "node:fs/promises";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, isAbsolute, join, resolve } from "node:path";

// ---------------------------------------------------------------------------
// glTF parsing helpers (no external deps)
// ---------------------------------------------------------------------------

const GLB_MAGIC = 0x46546c67; // 'glTF'
const CHUNK_JSON = 0x4e4f534a; // 'JSON'
const CHUNK_BIN = 0x004e4942; // 'BIN'

interface GltfNode {
	name?: string;
	mesh?: number;
	skin?: number;
	children?: number[];
	translation?: number[];
}

interface GltfAccessor {
	bufferView?: number;
	byteOffset?: number;
	componentType: number;
	count: number;
	type: string;
	normalized?: boolean;
	min?: number[];
	max?: number[];
}

interface GltfSkin {
	name?: string;
	joints: number[];
	skeleton?: number;
}

interface GltfJson {
	asset: { version: string; generator?: string };
	nodes?: GltfNode[];
	meshes?: {
		name?: string;
		primitives: { mode?: number; indices?: number; attributes: Record<string, number> }[];
	}[];
	skins?: GltfSkin[];
	animations?: { name?: string; channels: unknown[]; samplers: { input: number }[] }[];
	buffers?: { byteLength: number; uri?: string }[];
	bufferViews?: { buffer: number; byteOffset?: number; byteLength: number; byteStride?: number }[];
	accessors?: GltfAccessor[];
}

interface LoadedGltf {
	json: GltfJson;
	/** Buffer payload by buffer index (null = unresolved external) */
	buffers: (Uint8Array | null)[];
}

function parseGlb(data: Uint8Array): LoadedGltf {
	const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
	if (view.getUint32(0, true) !== GLB_MAGIC) throw new Error("Not a GLB file (bad magic)");
	const jsonChunkLen = view.getUint32(12, true);
	const jsonChunkType = view.getUint32(16, true);
	if (jsonChunkType !== CHUNK_JSON) throw new Error("GLB: first chunk is not JSON");
	const jsonText = new TextDecoder().decode(data.subarray(20, 20 + jsonChunkLen));
	const json = JSON.parse(jsonText) as GltfJson;
	const buffers: (Uint8Array | null)[] = [null];
	let offset = 20 + jsonChunkLen;
	// pad to 4 bytes
	offset = (offset + 3) & ~3;
	if (offset + 8 <= data.byteLength) {
		const binLen = view.getUint32(offset, true);
		const binType = view.getUint32(offset + 4, true);
		if (binType === CHUNK_BIN) {
			buffers[0] = data.subarray(offset + 8, offset + 8 + binLen);
		}
	}
	return { json, buffers };
}

async function loadGltf(path: string): Promise<LoadedGltf> {
	const raw = new Uint8Array(await readFile(path));
	if (path.toLowerCase().endsWith(".glb")) return parseGlb(raw);
	const json = JSON.parse(new TextDecoder().decode(raw)) as GltfJson;
	const dir = dirname(path);
	const buffers: (Uint8Array | null)[] = [];
	for (const buf of json.buffers ?? []) {
		if (!buf.uri) {
			buffers.push(null); // GLB-style embedded buffer in a .gltf is invalid here
			continue;
		}
		if (buf.uri.startsWith("data:")) {
			const b64 = buf.uri.slice(buf.uri.indexOf(",") + 1);
			buffers.push(Uint8Array.from(Buffer.from(b64, "base64")));
		} else {
			buffers.push(new Uint8Array(await readFile(resolve(dir, buf.uri))));
		}
	}
	return { json, buffers };
}

const COMPONENT_SIZE: Record<number, number> = {
	5120: 1, // BYTE
	5121: 1, // UNSIGNED_BYTE
	5122: 2, // SHORT
	5123: 2, // UNSIGNED_SHORT
	5125: 4, // UNSIGNED_INT
	5126: 4, // FLOAT
};

const NUM_COMPONENTS: Record<string, number> = {
	SCALAR: 1,
	VEC2: 2,
	VEC3: 3,
	VEC4: 4,
};

/** Read an accessor as a flat number array (handles float / normalized int weights). */
function readAccessor(gltf: LoadedGltf, index: number): Float64Array | null {
	const acc = gltf.json.accessors?.[index];
	if (!acc) return null;
	const compSize = COMPONENT_SIZE[acc.componentType];
	if (!compSize) return null;
	const numComp = NUM_COMPONENTS[acc.type] ?? 1;
	if (!acc.bufferView) return null;
	const bv = gltf.json.bufferViews![acc.bufferView];
	const buf = gltf.buffers[bv.buffer];
	if (!buf) return null;
	const start = (bv.byteOffset ?? 0) + (acc.byteOffset ?? 0);
	const stride = bv.byteStride ?? compSize * numComp;
	const dv = new DataView(buf.buffer, buf.byteOffset + start, buf.byteLength - start);
	const total = acc.count * numComp;
	const out = new Float64Array(total);
	let o = 0;
	for (let i = 0; i < acc.count; i++) {
		for (let c = 0; c < numComp; c++) {
			const p = i * stride + c * compSize;
			let v: number;
			switch (acc.componentType) {
				case 5126: v = dv.getFloat32(p, true); break;
				case 5121: v = dv.getUint8(p); break;
				case 5120: v = dv.getInt8(p); break;
				case 5123: v = dv.getUint16(p, true); break;
				case 5122: v = dv.getInt16(p, true); break;
				case 5125: v = dv.getUint32(p, true); break;
				default: v = 0;
			}
			if (acc.normalized && acc.componentType === 5121) v /= 255;
			else if (acc.normalized && acc.componentType === 5123) v /= 65535;
			else if (acc.normalized && acc.componentType === 5120) v /= 127;
			out[o++] = v;
		}
	}
	return out;
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

function normalizePath(ctxCwd: string, p: string): string {
	const stripped = p.startsWith("@") ? p.slice(1) : p;
	return isAbsolute(stripped) ? stripped : resolve(ctxCwd, stripped);
}

type Issue = { level: "error" | "warn" | "info"; msg: string };

// ---------------------------------------------------------------------------
// Tool: validate_rig
// ---------------------------------------------------------------------------

const ValidateRigParams = Type.Object({
	path: Type.String({ description: "Path to a .glb or .gltf character file" }),
	maxTriangles: Type.Optional(Type.Number({ description: "Triangle budget (default 3500, WoW-style low poly)" })),
	maxInfluences: Type.Optional(Type.Number({ description: "Max bone influences per vertex (default 4)" })),
	boneNamePattern: Type.Optional(
		Type.String({ description: "Regex bone names must match (default '^[A-Z][A-Za-z0-9_.-]*$' — uppercase first letter)" }),
	),
	minHeight: Type.Optional(Type.Number({ description: "Min model height in meters (default 0.5)" })),
	maxHeight: Type.Optional(Type.Number({ description: "Max model height in meters (default 4.0)" })),
});

async function validateRig(params: Static<typeof ValidateRigParams>, signal: AbortSignal | undefined, ctx: { cwd: string }) {
	const path = normalizePath(ctx.cwd, params.path);
	if (!existsSync(path)) throw new Error(`File not found: ${path}`);

	const gltf = await loadGltf(path);
	const issues: Issue[] = [];
	const err = (msg: string) => issues.push({ level: "error", msg });
	const warn = (msg: string) => issues.push({ level: "warn", msg });
	const info = (msg: string) => issues.push({ level: "info", msg });

	info(`glTF ${gltf.json.asset.version}${gltf.json.asset.generator ? ` — generator: ${gltf.json.asset.generator}` : ""}`);

	// --- Skin / joints -------------------------------------------------------
	const skins = gltf.json.skins ?? [];
	if (skins.length === 0) {
		err("No skin found — model is not rigged.");
	} else if (skins.length > 1) {
		err(`${skins.length} skins found; pipeline expects exactly one.`);
	} else {
		const skin = skins[0];
		info(`Skin "${skin.name ?? "unnamed"}" with ${skin.joints.length} joints.`);
		if (skin.skeleton === undefined) warn("Skin has no explicit skeleton root; Bevy uses the first joint's parent.");
		for (const j of skin.joints) {
			const node = gltf.json.nodes?.[j];
			if (!node) err(`Joint index ${j} does not exist in nodes.`);
			else if (!node.name || node.name.length === 0) err(`Joint node ${j} has no name — required for Bevy/animation debugging.`);
		}
		// single-root check
		const jointSet = new Set(skin.joints);
		const parentOf = new Map<number, number>();
		(gltf.json.nodes ?? []).forEach((n, i) => (n.children ?? []).forEach((c) => parentOf.set(c, i)));
		const roots = new Set<number>();
		for (const j of skin.joints) {
			let cur: number | undefined = j;
			while (cur !== undefined && !roots.has(cur)) {
				const parent = parentOf.get(cur);
				if (parent === undefined) { roots.add(cur); break; }
				if (!jointSet.has(parent)) break; // root of skin hierarchy
				cur = parent;
			}
		}
		if (roots.size > 1) warn(`Skin hierarchy has ${roots.size} roots; expected a single armature root.`);
	}

	// --- Bone naming convention ----------------------------------------------
	const pattern = new RegExp(params.boneNamePattern ?? "^[A-Z][A-Za-z0-9_.-]*$");
	if (skins.length > 0) {
		const bad = skins[0].joints
			.map((j) => gltf.json.nodes?.[j]?.name ?? "")
			.filter((n) => n.length > 0 && !pattern.test(n));
		if (bad.length > 0) err(`Bone naming convention violated (${bad.length}): ${bad.slice(0, 10).join(", ")}${bad.length > 10 ? ", …" : ""}`);
	}

	// --- Mesh / triangle budget ---------------------------------------------
	let totalTris = 0;
	let totalVerts = 0;
	for (const mesh of gltf.json.meshes ?? []) {
		for (const prim of mesh.primitives) {
			const mode = prim.mode ?? 4;
			if (mode !== 4) continue; // only triangles
			let triCount: number;
			if (prim.indices !== undefined) {
				const acc = gltf.json.accessors?.[prim.indices];
				triCount = acc ? Math.floor(acc.count / 3) : 0;
			} else {
				const posAcc = gltf.json.accessors?.[prim.attributes.POSITION];
				triCount = posAcc ? Math.floor(posAcc.count / 3) : 0;
			}
			totalTris += triCount;
			const posAcc = gltf.json.accessors?.[prim.attributes.POSITION];
			totalVerts += posAcc?.count ?? 0;
		}
	}
	info(`Total: ${totalTris} triangles, ${totalVerts} vertices.`);
	const maxTris = params.maxTriangles ?? 3500;
	if (totalTris > maxTris) err(`Triangle budget exceeded: ${totalTris} > ${maxTris}.`);

	// --- Height bounds (from POSITION accessor min/max, meters, Y-up) --------
	const heightBounds: [number, number][] = [];
	for (const mesh of gltf.json.meshes ?? []) {
		for (const prim of mesh.primitives) {
			const acc = gltf.json.accessors?.[prim.attributes.POSITION];
			if (acc?.min && acc?.max) heightBounds.push([acc.min[1], acc.max[1]]);
		}
	}
	if (heightBounds.length > 0) {
		const min = Math.min(...heightBounds.map((b) => b[0]));
		const max = Math.max(...heightBounds.map((b) => b[1]));
		const height = max - min;
		info(`Height: ${height.toFixed(2)} m (Y ${min.toFixed(2)} … ${max.toFixed(2)}).`);
		const minH = params.minHeight ?? 0.5;
		const maxH = params.maxHeight ?? 4.0;
		if (height < minH || height > maxH) warn(`Height ${height.toFixed(2)} m outside expected range ${minH}–${maxH} m.`);
	} else {
		warn("POSITION accessors lack min/max — cannot check height bounds.");
	}

	// --- Max influences per vertex --------------------------------------------
	const maxInf = params.maxInfluences ?? 4;
	let worst = 0;
	let vertsChecked = 0;
	for (const mesh of gltf.json.meshes ?? []) {
		for (const prim of mesh.primitives) {
			const weightsIdx = prim.attributes.WEIGHTS_0;
			if (weightsIdx === undefined) continue;
			const weights = readAccessor(gltf, weightsIdx);
			if (!weights) { warn("Could not read WEIGHTS_0 (unsupported encoding or missing buffer) — influence check skipped."); continue; }
			const numComp = NUM_COMPONENTS[gltf.json.accessors![weightsIdx].type] ?? 4;
			vertsChecked = weights.length / numComp;
			for (let v = 0; v < vertsChecked; v++) {
				let inf = 0;
				for (let c = 0; c < numComp; c++) if (weights[v * numComp + c] > 1e-6) inf++;
				if (inf > worst) worst = inf;
			}
		}
	}
	if (vertsChecked > 0) {
		info(`Max influences per vertex: ${worst}.`);
		if (worst > maxInf) err(`Max influences ${worst} exceeds limit ${maxInf}.`);
	} else if (skins.length > 0) {
		warn("No WEIGHTS_0 found although a skin exists.");
	}

	// --- Animations ----------------------------------------------------------
	const anims = gltf.json.animations ?? [];
	if (anims.length === 0) {
		warn("No animations in file.");
	} else {
		for (const [ai, anim] of anims.entries()) {
			let duration = 0;
			for (const s of anim.samplers) {
				const acc = gltf.json.accessors?.[s.input];
				if (acc?.max?.[0]) duration = Math.max(duration, acc.max[0]);
			}
			info(`Animation ${ai}: "${anim.name ?? "unnamed"}" — ${duration.toFixed(2)}s, ${anim.channels.length} channels.`);
		}
	}

	const errors = issues.filter((i) => i.level === "error");
	const warns = issues.filter((i) => i.level === "warn");
	const summary = errors.length > 0
		? `FAILED: ${errors.length} error(s), ${warns.length} warning(s)`
		: warns.length > 0
			? `PASSED with ${warns.length} warning(s)`
			: "PASSED";

	const text = [`validate_rig: ${path}`, summary, "", ...issues.map((i) => `[${i.level.toUpperCase()}] ${i.msg}`)].join("\n");

	return {
		content: [{ type: "text" as const, text }],
		details: {
			pass: errors.length === 0,
			summary,
			triangles: totalTris,
			vertices: totalVerts,
			maxInfluences: worst,
			animations: (gltf.json.animations ?? []).map((a) => a.name ?? "unnamed"),
			issues,
		},
	};
}

// ---------------------------------------------------------------------------
// Tool: export_gltf
// ---------------------------------------------------------------------------

const ExportGltfParams = Type.Object({
	blendFile: Type.String({ description: "Path to the .blend source file" }),
	outputFile: Type.String({ description: "Output .glb path" }),
	preset: Type.Optional(
		Type.String({ description: "Export preset (default 'character': GLB, skin + animations on, +Y up)" }),
	),
	exportAnimations: Type.Optional(Type.Boolean({ description: "Export animation clips (default true)" })),
	blenderPath: Type.Optional(Type.String({ description: "Blender binary (default $BLENDER_PATH or 'blender')" })),
});

async function exportGltf(pi: ExtensionAPI, params: Static<typeof ExportGltfParams>, signal: AbortSignal | undefined, onUpdate: ((r: { content: { type: "text"; text: string }[]; details: unknown }) => void) | undefined, ctx: { cwd: string }) {
	const blendFile = normalizePath(ctx.cwd, params.blendFile);
	const outputFile = normalizePath(ctx.cwd, params.outputFile);
	const script = join(ctx.cwd, "pipeline", "blender_export.py");

	if (!existsSync(blendFile)) throw new Error(`Blend file not found: ${blendFile}`);
	if (!existsSync(script)) throw new Error(`Export script not found: ${script} (run from the motion-mesh root)`);

	const blender = params.blenderPath ?? process.env.BLENDER_PATH ?? "blender";
	const animations = params.exportAnimations ?? true;
	const preset = params.preset ?? "character";

	onUpdate?.({
		content: [{ type: "text" as const, text: `Running ${blender} (headless) → ${outputFile}…` }],
		details: { phase: "exporting" },
	});

	const result = await pi.exec(
		blender,
		["--background", blendFile, "--python", script, "--", "--out", outputFile, "--preset", preset, animations ? "--animations" : "--no-animations"],
		{ signal, timeout: 10 * 60_000 },
	);

	const output = `${result.stdout}\n${result.stderr}`.trim();
	if (result.code !== 0) {
		throw new Error(`Blender export failed (exit ${result.code}${result.killed ? ", killed" : ""}):\n${output.slice(-4000)}`);
	}

	return {
		content: [{ type: "text" as const, text: `Exported ${blendFile} → ${outputFile}\n\n${output.slice(-2000)}` }],
		details: { outputFile, preset, exitCode: result.code },
	};
}

// ---------------------------------------------------------------------------
// Tool: check_bevy_import
// ---------------------------------------------------------------------------

const CheckBevyParams = Type.Object({
	assetPath: Type.String({ description: "Path to the .glb/.gltf asset to load" }),
	bevyVersion: Type.Optional(
		Type.String({ description: "Bevy crate version for the checker (default 0.20, e.g. '0.16' to match your game)" }),
	),
	timeoutSeconds: Type.Optional(Type.Number({ description: "Timeout in seconds (default 600; first run compiles Bevy)" })),
});

function pinBevyVersion(crateDir: string, version: string): boolean {
	const cargoPath = join(crateDir, "Cargo.toml");
	const content = readFileSync(cargoPath, "utf8");
	const match = content.match(/^(bevy\s*=\s*\{\s*version\s*=\s*")([^"]+)(")/m);
	if (!match) throw new Error("Could not find bevy dependency in bevy-check/Cargo.toml");
	if (match[2] === version) return false;
	writeFileSync(cargoPath, content.replace(match[0], `${match[1]}${version}${match[3]}`));
	return true;
}

async function checkBevyImport(pi: ExtensionAPI, params: Static<typeof CheckBevyParams>, signal: AbortSignal | undefined, onUpdate: ((r: { content: { type: "text"; text: string }[]; details: unknown }) => void) | undefined, ctx: { cwd: string }) {
	const assetPath = normalizePath(ctx.cwd, params.assetPath);
	if (!existsSync(assetPath)) throw new Error(`Asset not found: ${assetPath}`);

	const crateDir = join(ctx.cwd, "pipeline", "bevy-check");
	if (!existsSync(join(crateDir, "Cargo.toml"))) {
		throw new Error(`Bevy checker crate not found at ${crateDir}`);
	}
	if (params.bevyVersion) {
		const changed = pinBevyVersion(crateDir, params.bevyVersion);
		if (changed) onUpdate?.({ content: [{ type: "text" as const, text: `Pinned bevy ${params.bevyVersion}; rebuilding…` }], details: { phase: "pin" } });
	}

	let phase = "building";
	onUpdate?.({
		content: [{ type: "text" as const, text: "Compiling/running bevy-check (first run compiles Bevy; this can take minutes)…" }],
		details: { phase },
	});

	const result = await pi.exec("cargo", ["run", "--release", "--quiet", "--manifest-path", join(crateDir, "Cargo.toml"), "--", assetPath], {
		signal,
		timeout: (params.timeoutSeconds ?? 600) * 1000,
	});

	const output = `${result.stdout}\n${result.stderr}`.trim();
	const passed = result.code === 0;

	return {
		content: [
			{
				type: "text" as const,
				text: passed
					? `check_bevy_import: PASSED\nBevy loaded ${assetPath} without errors.\n\n${output.slice(-2000)}`
					: `check_bevy_import: FAILED (exit ${result.code})\n\n${output.slice(-4000)}`,
			},
		],
		details: { passed, exitCode: result.code, killed: result.killed },
	};
}

// ---------------------------------------------------------------------------
// Extension entry point
// ---------------------------------------------------------------------------

export default function motionMeshPipeline(pi: ExtensionAPI) {
	pi.registerTool({
		name: "validate_rig",
		label: "Validate Rig",
		description:
			"Validate a glTF/GLB character for the motion-mesh pipeline: single skin, named joints, bone naming convention, triangle & influence budgets, height bounds. Returns pass/fail with issues.",
		promptSnippet: "Validate a rigged glTF/GLB character against the motion-mesh pipeline rules",
		promptGuidelines: [
			"Use validate_rig after every rig/skin/mesh change; a goal is not complete unless validate_rig passes with 0 errors.",
		],
		parameters: ValidateRigParams,
		async execute(_toolCallId, params, signal, _onUpdate, ctx) {
			return validateRig(params, signal, ctx);
		},
	});

	pi.registerTool({
		name: "export_gltf",
		label: "Export glTF",
		description:
			"Export a .blend character to .glb via headless Blender using the motion-mesh 'character' preset (skin, animations, +Y up).",
		promptSnippet: "Export a .blend character to .glb with the motion-mesh Blender preset",
		promptGuidelines: [
			"Use export_gltf instead of hand-writing exporter scripts; it applies the pipeline's standard Blender glTF settings.",
		],
		parameters: ExportGltfParams,
		async execute(_toolCallId, params, signal, onUpdate, ctx) {
			return exportGltf(pi, params, signal, onUpdate, ctx);
		},
	});

	pi.registerTool({
		name: "check_bevy_import",
		label: "Check Bevy Import",
		description:
			"Load a glTF/GLB asset with the real Bevy asset stack (pipeline/bevy-check crate) and report success or the exact loader error. Compiles on first use.",
		promptSnippet: "Verify a glTF/GLB asset actually loads in Bevy",
		promptGuidelines: [
			"Use check_bevy_import as the final acceptance gate: an asset is done only when Bevy imports it without errors.",
		],
		parameters: CheckBevyParams,
		async execute(_toolCallId, params, signal, onUpdate, ctx) {
			return checkBevyImport(pi, params, signal, onUpdate, ctx);
		},
	});
}
