import path from 'node:path';
import CSSClient from '../../lib/cssClient.js';
import RemoteTarballExtractor from './remoteTarballExtractor.js';
export default class ScriptPuller {
    cssClient;
    destPath;
    scriptName;
    constructor(scriptName, destination) {
        this.cssClient = new CSSClient();
        this.destPath = this.normalizePath(scriptName, destination);
        this.scriptName = scriptName;
    }
    async pull() {
        const scripts = await this.cssClient.get('/scripts', { name: this.scriptName });
        if (!scripts || scripts.length === 0 || scripts[0]?.name !== this.scriptName) {
            throw new Error(`Script with name "${this.scriptName}" not found.`);
        }
        const { currentPackageId } = scripts[0];
        const packageUrl = (await this.cssClient.get(`/packages/${currentPackageId}`)).url;
        if (packageUrl) {
            await new RemoteTarballExtractor(packageUrl, this.destPath).extract();
        }
        else {
            throw new Error(`Package URL not found for packageId ${currentPackageId}`);
        }
    }
    normalizePath(scriptName, destination) {
        if (destination) {
            return destination;
        }
        const normalizedScriptName = scriptName.replaceAll(/[^a-zA-Z0-9-_]/g, '_');
        return path.join(process.cwd(), normalizedScriptName);
    }
}
