#!/usr/bin/env node
import { access, cp, readdir } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import chalk from "chalk";
import prompts from "prompts";
async function checkDirectoryExists(path$1) {
	try {
		await access(path$1);
		return true;
	} catch (_error) {
		return false;
	}
}
async function main() {
	const __dirname = path.dirname(fileURLToPath(import.meta.url));
	const templates = await readdir(path.join(__dirname, "templates"));
	const answers = await prompts([{
		type: "text",
		name: "directoryName",
		message: "Enter the name of the directory to generate into:",
		initial: "my-project"
	}, {
		type: "select",
		name: "templateName",
		message: "Choose a starter template:",
		choices: templates.map((template) => ({
			title: template,
			value: template
		}))
	}]);
	const targetDir = path.join(process.cwd(), answers.directoryName);
	const templateDir = path.join(__dirname, "templates", answers.templateName);
	const exists = await checkDirectoryExists(targetDir);
	if (exists) {
		process.stderr.write(chalk.yellow(`Directory ${targetDir} already exists.\n`));
		const { overwrite } = await prompts({
			type: "confirm",
			name: "overwrite",
			message: "Directory already exists. Do you want to overwrite it?",
			initial: false
		});
		if (!overwrite) {
			process.stderr.write(chalk.red("Aborting...\n"));
			process.exit(1);
		}
	}
	process.stderr.write(`Creating project in directory: ${targetDir}\n`);
	process.stderr.write(`Using template: ${answers.templateName}`);
	await cp(templateDir, targetDir, { recursive: true });
	process.stderr.write("Project created successfully.\n");
	process.stderr.write(chalk.green("Next steps:\n"));
	process.stderr.write(`cd ${answers.directoryName}\n`);
	process.stderr.write("npm install\n");
	process.stderr.write("npm start\n\n");
	process.stderr.write("Happy hacking!\n");
}
main();
