/**
 * windows-path-normalization.test.ts — Verify Windows backslash paths are
 * normalised to forward slashes before embedding in bash command strings.
 *
 * Regression test for #1436: on Windows, `cd C:\Users\user\project` in bash
 * strips backslashes (escape characters), producing `C:Usersuserproject`.
 */

import assert from "node:assert/strict";
import { describe, it } from "vitest";

function shellEscape(value: string): string {
	return `'${value.replace(/'/g, `'\\''`)}'`;
}

function bashPath(p: string): string {
	return shellEscape(p.replaceAll("\\", "/"));
}

describe("#1436: Windows backslash path normalization", () => {
	it("normalises backslash path to forward slashes", () => {
		assert.strictEqual(
			bashPath("C:\\Users\\user\\project"),
			"'C:/Users/user/project'",
		);
	});

	it("Unix paths pass through unchanged", () => {
		assert.strictEqual(
			bashPath("/home/user/project"),
			"'/home/user/project'",
		);
	});

	it("mixed separators are normalised", () => {
		assert.strictEqual(
			bashPath("C:\\Users/user\\project/src"),
			"'C:/Users/user/project/src'",
		);
	});

	it("single quotes in path are still properly escaped", () => {
		assert.strictEqual(
			bashPath("C:\\Users\\o'brien\\project"),
			"'C:/Users/o'\\''brien/project'",
		);
	});

	it("UNC paths are normalised", () => {
		assert.strictEqual(
			bashPath("\\\\server\\share\\dir"),
			"'//server/share/dir'",
		);
	});

	it("empty string is handled", () => {
		assert.strictEqual(bashPath(""), "''");
	});

	it("cd command uses forward slashes for Windows worktree path", () => {
		const windowsCwd = "C:\\Users\\user\\project\\.sf\\worktrees\\M001";
		const cdCommand = `cd ${bashPath(windowsCwd)}`;
		assert.strictEqual(
			cdCommand,
			"cd 'C:/Users/user/project/.sf/worktrees/M001'",
		);
		assert.ok(
			!cdCommand.includes("C:Users"),
			"mangled path C:Usersuserproject must not appear",
		);
	});

	it("orphan cleanup help command uses forward slashes", () => {
		const windowsWtDir = "C:\\Users\\user\\project\\.sf\\worktrees\\M001";
		const helpCommand = `rm -rf "${windowsWtDir.replaceAll("\\", "/")}"`;
		assert.strictEqual(
			helpCommand,
			'rm -rf "C:/Users/user/project/.sf/worktrees/M001"',
		);
	});
});
