import "@johnlindquist/kit"
import { Choice } from '@johnlindquist/kit';
const { globby } = await npm("globby");
const snippet_path = kenvPath('snippets');
const I_AM_THE_DANGER = false;
async function dangerous_evil_parse(content: string) {
	const evil_regex = /\$\$(.*?)\$\$/g;
	let match;
	let matches = [];
	while ((match = evil_regex.exec(content)) !== null) {
		matches.push(match);
	}
	for (let match of matches) {
		const script = match[1];
		const result = I_AM_THE_DANGER ? await eval(script) : ''; 
		content = content.replace(`$$${script}$$`, result);
	}
	return content;
}
async function set_with_cursor(content: string) {
	const cursor_index = content.indexOf('$CURSOR$');
	if (cursor_index === -1) {
		return false;
	}
	
	content = content.replace('$CURSOR$', '');
	await setSelectedText(content);
	
	
	await new Promise(resolve => setTimeout(resolve, 100));
	const target_cursor_position = content.length - cursor_index;
	const keystrokes = [];
	for (let i = 0; i < target_cursor_position; i++) {
		keystrokes.push(keystroke('left'));
	}
	await Promise.all(keystrokes);
	return true;
}
function files_to_choices(files: string[]): Choice[] {
	return files.map(file => ({
		name: path.basename(file, '').split('.')[0],
		value: file
	}));
}
async function get_snippet_files() {
	
	const snippet_files = await globby(`${snippet_path}/*`);
	if (process.platform == 'win32') {
		return snippet_files;
	}
	return snippet_files.map(file => file.replace(/\\/g, '/'));
}
async function get_content(snippet: string) {
	const snippet_content = await readFile(snippet, 'utf8');
	const snippet_lines = snippet_content.split('\n')
	
	return snippet_lines
		.slice(snippet_lines.findIndex(line => !line.startsWith('//')))
		.join('\n');
}
async function insert_selection(content: string) {
	if (content.includes('$SELECTION$') === false) {
		return content;
	}
	const selection = await getSelectedText();
	content = content.replace('$SELECTION$', selection);
	return content;
}
async function insert_clipboard(content: string) {
	if (content.includes('$CLIPBOARD$') === false) {
		return content;
	}
	const text = await clipboard.readText();
	content = content.replace('$CLIPBOARD$', text);
	return content;
}
const snippet_file = await arg("Which snippet?", files_to_choices(await get_snippet_files()));
let content = await get_content(snippet_file);
content = await insert_selection(content);
content = await insert_clipboard(content);
content = await dangerous_evil_parse(content);
if (!(await set_with_cursor(content))) {
	await setSelectedText(content);
}