// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: GPL-3.0-or-later

import { accessSync, constants } from "node:fs";
import { isAbsolute, resolve as resolvePath, sep } from "node:path";
import { ToolInputError } from "../../util/errors.js";

const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;

function normalizeAtPrefix(filePath: string): string {
	return filePath.startsWith("@") ? filePath.slice(1) : filePath;
}

function fileExists(path: string): boolean {
	try {
		accessSync(path, constants.F_OK);
		return true;
	} catch {
		return false;
	}
}

function tryMacOSScreenshotPath(filePath: string): string {
	return filePath.replace(/ (AM|PM)\./g, "\u202F$1.");
}

function tryNFDVariant(filePath: string): string {
	return filePath.normalize("NFD");
}

function tryCurlyQuoteVariant(filePath: string): string {
	return filePath.replace(/'/g, "\u2019");
}

export function expandPath(filePath: string): string {
	let result = filePath.replace(UNICODE_SPACES, " ");
	result = normalizeAtPrefix(result);

	// NOTE: tilde expansion is intentionally omitted.
	// In a workspace-sandboxed context, expanding ~ to the user's home
	// directory would bypass workspace containment. Tildes are treated
	// as literal path characters.

	return result;
}

export function resolveToCwd(filePath: string, cwd: string): string {
	const expanded = expandPath(filePath);
	if (isAbsolute(expanded)) {
		return expanded;
	}
	return resolvePath(cwd, expanded);
}

export function resolveReadPath(filePath: string, cwd: string): string {
	const resolved = resolveToCwd(filePath, cwd);

	if (fileExists(resolved)) {
		return resolved;
	}

	const variants = [tryNFDVariant, tryMacOSScreenshotPath, tryCurlyQuoteVariant];
	for (const variant of variants) {
		const candidate = variant(resolved);
		if (candidate !== resolved && fileExists(candidate)) {
			return candidate;
		}
	}

	return resolved;
}

export function ensureWorkspacePath(workspacePath: string, targetPath: string): string {
	const resolved = resolvePath(workspacePath, targetPath);
	const root = workspacePath.endsWith(sep) ? workspacePath : `${workspacePath}${sep}`;

	if (resolved === workspacePath || resolved.startsWith(root)) {
		return resolved;
	}

	throw new ToolInputError(`Path escapes workspace: ${targetPath}`);
}
