import fs from 'node:fs';
import path from 'node:path';
import OutputManager from '../outputManager.js';
import ScriptBuilder from './scriptBuilder.js';
import ScriptPackager from './scriptPackager.js';
export default class PackageCreator {
    destinationPath;
    scriptName;
    srcPath;
    constructor(srcPath, destinationPath) {
        this.srcPath = srcPath;
        this.destinationPath = this.ensureTgzExtension(destinationPath);
        this.scriptName = path.basename(srcPath);
    }
    async create() {
        // Validate destination directory exists
        const destinationDir = path.dirname(this.destinationPath);
        if (!fs.existsSync(destinationDir)) {
            throw new Error(`Destination directory does not exist: ${destinationDir}`);
        }
        // Build the script
        const builder = new ScriptBuilder(this.srcPath);
        const buildImage = await builder.build();
        // Package the script (returns path to .tgz file)
        const packager = new ScriptPackager(this.srcPath, this.scriptName, buildImage);
        await packager.stage();
        const packagePath = await packager.package();
        // Copy the .tgz file to destination
        fs.copyFileSync(packagePath, this.destinationPath);
        OutputManager.detail(`Created package at ${this.destinationPath}`);
    }
    ensureTgzExtension(destinationPath) {
        const ext = path.extname(destinationPath);
        if (ext === '.tar.gz' || ext === '.tgz') {
            return destinationPath;
        }
        return `${destinationPath}.tgz`;
    }
}
