"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.command = void 0;
const tslib_1 = require("tslib");
const fs_1 = require("fs");
const path_1 = tslib_1.__importDefault(require("path"));
const file_resolver_1 = require("@markuplint/file-resolver");
const api_1 = require("../api");
const debug_1 = require("../debug");
const output_1 = require("./output");
async function command(files, options, apiOptions) {
    var _a;
    const fix = options.fix;
    const configFile = options.config && path_1.default.join(process.cwd(), options.config);
    const locale = options.locale;
    const searchConfig = options.searchConfig;
    const ignoreExt = options.ignoreExt;
    const importPresetRules = options.importPresetRules;
    const verbose = options.verbose;
    const fileList = await (0, file_resolver_1.resolveFiles)(files);
    if (debug_1.log.enabled) {
        (0, debug_1.log)('File list: %O', fileList.map(f => f.path));
        (0, debug_1.log)('Config: %s', configFile || 'N/A');
        (0, debug_1.log)('Fix option: %s', fix);
    }
    const format = (_a = options.format) === null || _a === void 0 ? void 0 : _a.toLowerCase().trim();
    let hasError = false;
    const jsonOutput = [];
    for (const file of fileList) {
        const engine = new api_1.MLEngine(file, {
            configFile,
            fix,
            locale,
            noSearchConfig: !searchConfig,
            ignoreExt,
            importPresetRules,
            debug: verbose,
            ...apiOptions,
        });
        const result = await engine.exec();
        if (!result) {
            continue;
        }
        if (!hasError && result.violations.length) {
            hasError = true;
        }
        if (fix) {
            (0, debug_1.log)('Overwrite file: %s', result.filePath);
            await fs_1.promises.writeFile(result.filePath, result.fixedCode, { encoding: 'utf8' });
            process.stdout.write(`markuplint: Fix "${result.filePath}"\n`);
        }
        else {
            if (format === 'json') {
                jsonOutput.push(...result.violations.map(v => ({
                    ...v,
                    filePath: result.filePath,
                })));
                continue;
            }
            (0, debug_1.log)('Output reports');
            (0, output_1.output)(result, options);
        }
    }
    if (format === 'json') {
        process.stdout.write(JSON.stringify(jsonOutput, null, 2) + '\n');
        return false;
    }
    return hasError;
}
exports.command = command;
