import { $ } from 'bun';

import path from 'path';
import fs from 'fs/promises';
import { buildHTML } from "./html";
import select from '@inquirer/select';
import { isGame, getGames } from './isGame';

const outDir = path.resolve(import.meta.dir, '..', 'dist');
await fs.mkdir(outDir, { recursive: true });

const publish = process.env.PUBLISH_LOCATION;

const args = process.argv.slice(2);
const local = args.includes('--local');
let game = args.find(a => !a.startsWith('-')) ?? '';

while (!await isGame(game)) {
    game = await select({
        message: 'Game to build:',
        choices: (await getGames()).map(game => ({ value: game.name })),
    });
}
console.log(`Building ${game}...`);
const html = await buildHTML(game, { production: true, local });

if (!html) {
    process.exit(1);
}
const filePath = path.resolve(outDir, `${game}.html`);
await Bun.write(filePath, html);

if (publish && !local) {
    console.log(`Publishing ${game}...`);
    const result = await $`scp "${filePath}" "${publish}${game}.html"`;
    if (result.exitCode === 0) {
        console.log(`Build successful: ${process.env.PUBLISH_URL}${game}`);
    }
}