import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from 'vitest';

import {
	buildRepositoryVcsContextBlock,
	detectRepositoryVcsContext,
} from "../repository-vcs-context.ts";

function tempRepo(): string {
	return mkdtempSync(join(tmpdir(), "sf-vcs-context-"));
}

test("detectRepositoryVcsContext_when_plain_git_repo_uses_git", () => {
	const root = tempRepo();
	mkdirSync(join(root, ".git"));

	const context = detectRepositoryVcsContext(join(root, "src"));

	assert.equal(context.kind, "git");
	assert.equal(context.root, root);
	assert.equal(context.pushWrapper, null);
});

test("detectRepositoryVcsContext_when_jj_marker_exists_prefers_jj", () => {
	const root = tempRepo();
	mkdirSync(join(root, ".git"));
	mkdirSync(join(root, ".jj"));

	const context = detectRepositoryVcsContext(root);

	assert.equal(context.kind, "jj");
	assert.equal(context.root, root);
});

test("buildRepositoryVcsContextBlock_when_git_without_wrapper_allows_git", () => {
	const root = tempRepo();
	mkdirSync(join(root, ".git"));

	const block = buildRepositoryVcsContextBlock(root);

	assert.match(block, /Detected VCS: Git/);
	assert.match(block, /normal Git commands are appropriate/);
	assert.doesNotMatch(block, /ACE/);
});

test("buildRepositoryVcsContextBlock_when_repo_wrapper_exists_keeps_it_local", () => {
	const root = tempRepo();
	mkdirSync(join(root, ".git"));
	mkdirSync(join(root, "scripts"));
	writeFileSync(join(root, "scripts", "safe_push.sh"), "#!/bin/sh\n");

	const block = buildRepositoryVcsContextBlock(root);

	assert.match(block, /Repo-owned push wrapper detected: scripts\/safe_push\.sh/);
	assert.match(block, /Do not apply push rules from sibling/);
});
