import { Md5 } from "ts-md5";
import DockerManager from "../docker/dockerManager.js";
import ImageBuilder from "../images/imageBuilder.js";
import ImagePuller from "../images/imagePuller.js";
import OutputManager from '../outputManager.js';
import PackageConfig from "../packageConfig.js";
import StatusManager from "../statusManager.js";
export default class ScriptBuilder {
    scriptPath;
    constructor(scriptPath) {
        this.scriptPath = scriptPath;
    }
    async build() {
        const packageConfig = new PackageConfig(this.scriptPath);
        if (!packageConfig.isAvailable()) {
            OutputManager.warn("No package configuration found, so skipping build.");
            OutputManager.newline();
            return;
        }
        const parsedPackageConfig = packageConfig.parse();
        const buildConfig = parsedPackageConfig.build;
        if (!buildConfig) {
            OutputManager.warn("No build configuration found, so skipping build.");
            OutputManager.newline();
            return;
        }
        StatusManager.startTask("Building script image");
        const docker = await DockerManager.get();
        OutputManager.detail("Pulling base image");
        const imagePuller = new ImagePuller(docker, buildConfig.image);
        const baseImage = await imagePuller.pull();
        const executorImageName = `cloudscripts-build-${Md5.hashAsciiStr(this.scriptPath)}`;
        const imageBuildParams = {
            artifacts: buildConfig.artifacts,
            baseImage,
            buildCommand: buildConfig.command,
            buildWorkDirOverride: buildConfig.workDir,
            srcPaths: buildConfig.context,
            srcRoot: this.scriptPath
        };
        OutputManager.detail(`Building image "${executorImageName}"`);
        const imageBuilder = new ImageBuilder(docker, executorImageName);
        const image = await imageBuilder.build(imageBuildParams);
        if (buildConfig.devArtifacts && Object.keys(buildConfig.devArtifacts).length > 0) {
            OutputManager.detail("Copying dev artifacts");
            const devArtifacts = Object.fromEntries(Object.entries(buildConfig.devArtifacts).filter(([_key, value]) => value !== null));
            await image.getFiles(this.scriptPath, devArtifacts);
        }
        StatusManager.finishTask();
        return image;
    }
}
