"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.format = format;
const taskSelection_1 = require("../taskSelection");
const taskUtils_1 = require("../taskUtils");
const uploadLog_1 = require("../uploadLog");
const validate_1 = require("../apps/validate");
async function format(pathOrName) {
    const selection = (0, taskSelection_1.selectTasks)(pathOrName);
    if (selection.errors.length > 0) {
        (0, taskSelection_1.reportTaskErrors)(selection.errors, 'project format');
        process.exitCode = 1;
        return;
    }
    const tasks = selection.tasks;
    const warnings = selection.warnings;
    if (tasks.length === 0) {
        (0, uploadLog_1.printTaskSummary)([], warnings, { action: 'format' });
        return;
    }
    const results = [];
    for (const task of (0, taskUtils_1.sortTasks)(tasks)) {
        try {
            if (task.kind === 'app') {
                const ran = await (0, validate_1.runFormatScript)(task);
                if (!ran) {
                    throw new Error(`project format requires a package.json "format" script for app "${task.name}".`);
                }
                const entry = {
                    action: 'format',
                    status: 'success',
                    entityType: 'app',
                    entityId: task.name,
                    catalogue: task.cataloguePath,
                };
                results.push(entry);
                console.log((0, uploadLog_1.formatTaskLogLine)(entry));
            }
            else {
                throw new Error(`project format does not support ${task.kind} "${task.name}".`);
            }
        }
        catch (error) {
            const message = error?.message ?? String(error);
            const entry = {
                action: 'format',
                status: 'error',
                entityType: task.kind,
                entityId: task.name,
                catalogue: task.cataloguePath,
                detail: message,
            };
            results.push(entry);
            console.log((0, uploadLog_1.formatTaskLogLine)(entry));
        }
    }
    (0, uploadLog_1.printTaskSummary)(results, warnings, { action: 'format' });
}
