// Figurement sync: keeps a Figurement scene up to date with a model file your CAD tool exports.
//
// Every time the file changes, it is uploaded to the scene in update mode: parts are matched to the ones already in
// the scene by name and hierarchy and get the new geometry and placement, keeping their materials; new parts are
// added; parts the file no longer has are reported (or removed with --remove-missing).
//
//   export FIGUREMENT_API_KEY=...   # Account → API Keys
//   deno run --allow-net --allow-read --allow-env https://app.figurement.com/docs/tools/figurement-sync.ts \
//     --scene sc123abc --watch ~/CAD/exports/assembly.glb
//
// --watch takes a file or a folder (the most recently changed .glb/.gltf/.obj file in it is uploaded). --once uploads
// the current file and exits, for a macro's "send to Figurement" button. --server points at another Figurement.
// Needs Deno 2 (https://deno.com). Uses nothing but Deno's own APIs, so it can be read in one go.

const MODEL_EXTENSIONS = ['.glb', '.gltf', '.obj'];
/** A file counts as written once its size and time have not changed for this long. */
const SETTLE_MS = 1500;

interface Options {
	server: string;
	scene: string;
	watch: string;
	removeMissing: boolean;
	once: boolean;
	apiKey: string;
}

interface Part {
	name: string;
	path: string;
}

interface Report {
	matched: number;
	updated: Part[];
	moved: Part[];
	keptAnimated: Part[];
	added: Part[];
	missing: Part[];
	removed: Part[];
}

function usage(message: string): never {
	console.error(`${message}

Usage: figurement-sync --scene <scene id> --watch <file or folder> [--remove-missing] [--once] [--server <url>]
The API key is read from FIGUREMENT_API_KEY.`);
	Deno.exit(2);
}

function parseOptions(args: string[]): Options {
	let server = 'https://app.figurement.com';
	let scene = '';
	let watch = '';
	let removeMissing = false;
	let once = false;
	for (let i = 0; i < args.length; i++) {
		const option = args[i];
		const value = () => args[++i] ?? usage(`${option} needs a value`);
		if (option === '--scene') scene = value();
		else if (option === '--watch') watch = value();
		else if (option === '--server') server = value().replace(/\/+$/, '');
		else if (option === '--remove-missing') removeMissing = true;
		else if (option === '--once') once = true;
		else usage(`Unknown option ${option}`);
	}
	const apiKey = Deno.env.get('FIGUREMENT_API_KEY') ?? '';
	if (!scene) usage('--scene is required: the scene id, from its URL (/scenes/<id>)');
	if (!watch) usage('--watch is required');
	if (!apiKey) usage('Set FIGUREMENT_API_KEY to an API key (Account → API Keys)');
	return { server, scene, watch, removeMissing, once, apiKey };
}

function isModel(path: string): boolean {
	return MODEL_EXTENSIONS.some((extension) => path.toLowerCase().endsWith(extension));
}

/** The model file to upload: `watch` itself, or the most recently changed model file in it. */
async function currentModel(watch: string): Promise<string | undefined> {
	if ((await Deno.stat(watch)).isFile) return watch;
	let newest: { path: string; time: number } | undefined;
	for await (const entry of Deno.readDir(watch)) {
		if (!entry.isFile || !isModel(entry.name)) continue;
		const path = `${watch.replace(/\/+$/, '')}/${entry.name}`;
		const time = (await Deno.stat(path)).mtime?.getTime() ?? 0;
		if (!newest || time > newest.time) newest = { path, time };
	}
	return newest?.path;
}

/** Waits until a CAD tool has finished writing `path`: its size and time stay the same for SETTLE_MS. */
async function settled(path: string): Promise<void> {
	let last = '';
	for (;;) {
		const info = await Deno.stat(path);
		const now = `${info.size}:${info.mtime?.getTime()}`;
		if (now === last) return;
		last = now;
		await new Promise((resolve) => setTimeout(resolve, SETTLE_MS));
	}
}

async function digest(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
	const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
	return Array.from(hash, (byte) => byte.toString(16).padStart(2, '0')).join('');
}

async function upload(options: Options, path: string, bytes: Uint8Array<ArrayBuffer>): Promise<Report> {
	const form = new FormData();
	form.set('file', new File([bytes], path.split('/').pop() ?? 'model.glb'));
	const query = new URLSearchParams({ mode: 'update' });
	if (options.removeMissing) query.set('removeMissing', '1');
	const url = `${options.server}/api/scenes/${encodeURIComponent(options.scene)}/import?${query}`;
	for (let attempt = 1;; attempt++) {
		const response = await fetch(url, {
			method: 'POST',
			headers: { Authorization: `Bearer ${options.apiKey}` },
			body: form,
		});
		// 409: the scene is briefly busy (being reverted, or another import); try again.
		if (response.status === 409 && attempt < 5) {
			await new Promise((resolve) => setTimeout(resolve, 2000 * attempt));
			continue;
		}
		if (!response.ok) throw new Error(`${response.status} ${(await response.text()).slice(0, 300)}`);
		return (await response.json()).report;
	}
}

function describe(report: Report): string {
	const lines = [`matched ${report.matched} parts`];
	const list = (label: string, parts: Part[]) => {
		if (parts.length === 0) return;
		const names = parts.slice(0, 10).map((part) => part.name || part.path).join(', ');
		lines.push(`${label} ${parts.length}: ${names}${parts.length > 10 ? ', …' : ''}`);
	};
	list('new geometry', report.updated);
	list('moved', report.moved);
	list('animated, left in place', report.keptAnimated);
	list('added', report.added);
	list('no longer in the file (still in the scene)', report.missing);
	list('removed', report.removed);
	return lines.join('\n  ');
}

async function main() {
	const options = parseOptions(Deno.args);
	let lastDigest = '';

	/** Uploads the current model if it changed; false if it could not. Never throws. */
	const sync = async (): Promise<boolean> => {
		const time = () => new Date().toLocaleTimeString();
		try {
			const path = await currentModel(options.watch);
			if (!path) {
				console.error(`${time()} No .glb, .gltf or .obj file at ${options.watch}`);
				return false;
			}
			await settled(path);
			const bytes = await Deno.readFile(path);
			const hash = await digest(bytes);
			if (hash === lastDigest) return true;
			const report = await upload(options, path, bytes);
			lastDigest = hash;
			console.log(`${time()} ${path} → scene ${options.scene}\n  ${describe(report)}`);
			return true;
		} catch (error) {
			// A CAD tool replacing the file mid-export lands here too; the next change retries.
			console.error(`${time()} Sync failed: ${error instanceof Error ? error.message : error}`);
			return false;
		}
	};

	if (options.once) Deno.exit((await sync()) ? 0 : 1);

	// Watching starts before the first sync, so an export saved while it uploads is not missed.
	const watcher = Deno.watchFs(options.watch);
	let running = Promise.resolve();
	let queued = false;
	/** One sync at a time; changes during a sync are picked up by the one queued after it. */
	const queueSync = () => {
		if (queued) return;
		queued = true;
		running = running.then(async () => {
			queued = false;
			await sync();
		});
	};
	queueSync();
	console.log(`Watching ${options.watch} (Ctrl+C to stop)`);
	for await (const event of watcher) {
		if (event.kind !== 'remove' && event.paths.some(isModel)) queueSync();
	}
}

if (import.meta.main) {
	await main();
}
