import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

// Skip in non-TTY environments — init enters the interactive setup flow.
if (!process.stdin.isTTY || !process.stdout.isTTY) {
	console.log("  SKIP  test-init (no TTY)");
	process.exit(0);
}

const tmpDir = mkdtempSync(join(tmpdir(), "sf-smoke-init-"));

try {
	const defaultBinary = process.execPath;
	const defaultArgs = [
		join(import.meta.dirname, "..", "..", "dist", "loader.js"),
	];
	const binary = process.env.SF_SMOKE_BINARY || defaultBinary;
	const args = process.env.SF_SMOKE_BINARY
		? ["init"]
		: [...defaultArgs, "init"];

	execFileSync(binary, args, {
		encoding: "utf8",
		timeout: 30_000,
		cwd: tmpDir,
		env: { ...process.env, SF_NON_INTERACTIVE: "1" },
	});

	const sfDir = join(tmpDir, ".sf");
	if (!existsSync(sfDir)) {
		console.error(`.sf directory not created in ${tmpDir}`);
		process.exit(1);
	}
} finally {
	rmSync(tmpDir, { recursive: true, force: true });
}
