import { build } from 'esbuild';
import { resolve, dirname } from 'path';
import { mkdirSync } from 'fs';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const entryPoints = [
    resolve(__dirname, 'src/index.ts')
];

try {
    mkdirSync(resolve(__dirname, 'dist'), { recursive: true });
} catch (e) { }

console.log(`Building entry point...`);

build({
    entryPoints: entryPoints,
    bundle: true,
    platform: 'node',
    target: 'node18',
    outdir: resolve(__dirname, 'dist'),
    format: 'esm',
    loader: {
        '.ts': 'ts',
        '.js': 'js',
    },
    external: ["playwright", "crawlee", "axios", "cheerio", "fs", "path", "os", "http", "https", "url", "stream", "util", "child_process"],
}).then(() => {
    console.log("Build succeeded!");
}).catch((e) => {
    if (e.errors) {
        console.error("Build failed with errors:");
        e.errors.forEach(err => console.error(`  ${err.text} at ${err.location?.file}:${err.location?.line}`));
    } else {
        console.error("Build failed:", e);
    }
    process.exit(1);
});
