import path from 'node:path';
import constants from '../constants.js';
import NameNormalizer from '../nameNormalizer.js';
import OutputManager from '../outputManager.js';
import ScriptBuilder from './scriptBuilder.js';
import ScriptPackager from './scriptPackager.js';
import ScriptPublisher from './scriptPublisher.js';
export default class ScriptPusher {
    force;
    scriptName;
    srcPath;
    constructor(explicitName, force, srcPath) {
        this.force = force;
        this.scriptName = this.getScriptName(explicitName, srcPath);
        this.srcPath = srcPath;
    }
    async push() {
        const publisher = new ScriptPublisher(this.scriptName, this.srcPath);
        if (await publisher.hasExistingInstance() && !this.force) {
            throw new Error(`Script with name "${this.scriptName}" already exists and \`--force\` option not specified.`);
        }
        const builder = new ScriptBuilder(this.srcPath);
        const buildImage = await builder.build();
        const packager = new ScriptPackager(this.srcPath, this.scriptName, buildImage);
        await packager.stage();
        const packagePath = await packager.package();
        await publisher.publish(packagePath);
    }
    getScriptName(explicitName, srcPath) {
        if (explicitName) {
            const normalizedName = NameNormalizer.normalize(explicitName);
            if (explicitName !== normalizedName) {
                throw new Error(`Script name is not valid. Only alphanumeric characters, hyphens and underscores are allowed with a maximum length of ${constants.NAME_NORMALIZER_MAX_LENGTH} characters.`);
            }
            return explicitName;
        }
        let scriptName = path.basename(srcPath);
        const normalizedName = NameNormalizer.normalize(scriptName);
        if (scriptName !== normalizedName) {
            scriptName = normalizedName;
            OutputManager.warn(`Script will be renamed to "${scriptName}" for compliance with name requirements.`);
        }
        return scriptName;
    }
}
