"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = build;
const taskSelection_1 = require("../taskSelection");
const taskUtils_1 = require("../taskUtils");
const uploadLog_1 = require("../uploadLog");
const apps_1 = require("../apps");
const model_artifacts_1 = require("../assets/model-artifacts");
async function build(pathOrName) {
    const selection = (0, taskSelection_1.selectTasks)(pathOrName);
    if (selection.errors.length > 0) {
        (0, taskSelection_1.reportTaskErrors)(selection.errors, 'project build');
        process.exitCode = 1;
        return;
    }
    const tasks = selection.tasks;
    const warnings = selection.warnings;
    if (tasks.length === 0) {
        (0, uploadLog_1.printTaskSummary)([], warnings, { action: 'build' });
        return;
    }
    const results = [];
    for (const task of (0, taskUtils_1.sortTasks)(tasks)) {
        const entityId = task.name;
        try {
            if (task.kind === 'app') {
                await (0, apps_1.validateAppTask)(task);
                await (0, apps_1.buildApp)(task);
            }
            else if (task.kind === 'asset' || task.kind === 'owned-asset') {
                const generated = await (0, model_artifacts_1.prepareModel3DAssetArtifacts)(task);
                if (!generated) {
                    throw new Error(`project build does not support ${task.kind} "${entityId}" because it has no local build step.`);
                }
            }
            else {
                throw new Error(`project build does not support ${task.kind} "${entityId}".`);
            }
            const entry = {
                action: 'build',
                status: 'success',
                entityType: task.kind,
                entityId,
                catalogue: task.cataloguePath,
            };
            results.push(entry);
            console.log((0, uploadLog_1.formatTaskLogLine)(entry));
        }
        catch (error) {
            const message = (error?.message ?? String(error));
            const entry = {
                action: 'build',
                status: 'error',
                entityType: task.kind,
                entityId,
                catalogue: task.cataloguePath,
                detail: message,
            };
            results.push(entry);
            console.log((0, uploadLog_1.formatTaskLogLine)(entry));
        }
    }
    (0, uploadLog_1.printTaskSummary)(results, warnings, { action: 'build' });
}
