import CSSClient from '../../lib/cssClient.js';
import TablePrinter from '../../lib/tablePrinter.js';
import InfoDisplayer from '../infoDisplayer.js';
import OutputManager from '../outputManager.js';
export default class ScriptInfoDisplayer {
    cssClient;
    scriptName;
    constructor(scriptName) {
        this.cssClient = new CSSClient();
        this.scriptName = scriptName;
    }
    async displayInfo() {
        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 script = scripts[0];
        const { currentPackageId } = script;
        const packageStatus = currentPackageId ? await this.cssClient.get(`/packages/${currentPackageId}/status`) : null;
        const runSpecs = await this.cssClient.get('/runSpecs', { scriptId: script.id });
        const imageNames = (await this.cssClient.get('/images'))
            // eslint-disable-next-line unicorn/no-array-reduce
            .reduce((acc, rs) => {
            acc[rs.id] = rs.name;
            return acc;
        }, {});
        /* eslint-disable perfectionist/sort-maps */
        const scriptInfoDisplayer = new InfoDisplayer(new Map([
            ['Script name', this.scriptName],
            ['Script ID', script.id],
            ['Last updated', new Date(script.updatedAt).toLocaleString()]
        ]));
        /* eslint-enable perfectionist/sort-maps */
        scriptInfoDisplayer.displayAsTable();
        const packageInfoDisplayer = new InfoDisplayer(new Map([
            ['Current package ID', currentPackageId || 'None'],
            currentPackageId ? ['Available', packageStatus.available ? 'Yes' : 'No'] : null
        ].filter((entry) => entry !== null) // Filter out null values
        ));
        packageInfoDisplayer.displayAsTable();
        const runSpecTableData = runSpecs.map((runSpec) => ({
            command: Array.isArray(runSpec.command) && runSpec.command.length > 0 ? runSpec.command.join(' ') : 'N/A',
            hasEgress: runSpec.hasEgress ? 'Yes' : 'No',
            imageName: imageNames[runSpec.imageId],
            name: runSpec.name
        }));
        new TablePrinter(OutputManager.bold('Run specs'), runSpecTableData, [
            { key: 'name', name: 'Name' },
            { key: 'imageName', name: 'Image' },
            { key: 'hasEgress', name: 'Egress' },
            { key: 'command', name: 'Command' }
        ]).print();
    }
}
