"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.gatherClocMetrics = gatherClocMetrics;
const runner_1 = require("./runner");
const exclusions_1 = require("./exclusions");
const languages_1 = require("../../languages");
const SKIP_KEYS = new Set(['header', 'SUM']);
/** Gather metrics from cloc --json. */
function gatherClocMetrics(cwd) {
    // --timeout 0 disables per-file timeout (suppresses warning that breaks JSON parse)
    // getClocExcludeFlags emits BOTH `--exclude-dir` (basenames)
    // AND `--fullpath --not-match-d` (Perl regex on full path) so multi-segment
    // `.dxkit-ignore` entries like `app/vendor/generated/` exclude the
    // correct subtree instead of every dir named `app`.
    const excludeFlags = (0, exclusions_1.getClocExcludeFlags)(cwd);
    const flags = `--json --timeout 0 ${excludeFlags}`;
    // Try system cloc first (faster), then npx as fallback
    const result = (0, runner_1.runJSON)(`cloc . ${flags}`, cwd, 180000);
    if (!result || !result.SUM) {
        const fallback = (0, runner_1.runJSON)(`npx cloc . ${flags}`, cwd, 180000);
        if (!fallback || !fallback.SUM) {
            return { toolsUnavailable: ['cloc'] };
        }
        return parseClocResult(fallback);
    }
    return parseClocResult(result);
}
function parseClocResult(result) {
    // D073 (2.4.7): filter cloc's per-language summary to the names
    // declared by registered packs. Pre-D073 the language table + the
    // `totalLines` denominator included markup/data formats (JSON,
    // XML, CSV, YAML, Markdown) that cloc lists alongside "real"
    // languages. On the .NET WinForms benchmark the 1.6M-line JSON + 1.3M-line XML
    // dragged the quality "Comment Ratio" from a true ~25% (C#
    // comments / C# total) to 4.3% (all comments / all-cloc-totals).
    // The pack registry is the canonical source of "what counts as
    // source code"; cloc's own categorization is intentionally broad.
    const packLanguages = new Set((0, languages_1.allClocLanguageNames)());
    const clocLanguages = [];
    let totalCode = 0;
    let totalComment = 0;
    let totalBlank = 0;
    for (const [key, value] of Object.entries(result)) {
        if (SKIP_KEYS.has(key))
            continue;
        const lang = value;
        if (typeof lang.nFiles !== 'number')
            continue;
        if (!packLanguages.has(key))
            continue;
        clocLanguages.push({
            language: key,
            files: lang.nFiles,
            code: lang.code,
            comment: lang.comment,
            blank: lang.blank,
        });
        totalCode += lang.code;
        totalComment += lang.comment;
        totalBlank += lang.blank;
    }
    // Sort by code lines descending
    clocLanguages.sort((a, b) => b.code - a.code);
    // D057 (2.4.7): cloc no longer writes `sourceFiles`. Pre-fix the
    // mergeLayer2 overlay blindly overwrote generic's find-based count
    // with cloc's, which (a) included markup/data files (JSON/XML/CSV)
    // that aren't source, and (b) on the .NET WinForms benchmark was broken by D055.
    // Field ownership: generic.ts owns sourceFiles; cloc owns line
    // counts + language breakdown. (Class-fix tracked as G_v4_8 in
    // recipe v4 — "each gather declares which fields it owns; merger
    // errors on overlap".)
    // totalLines is now derived from the pack-filtered language sum so
    // it represents source lines, not source+markup+data lines.
    return {
        totalLines: totalCode + totalComment + totalBlank,
        clocLanguages,
        toolsUsed: ['cloc'],
    };
}
//# sourceMappingURL=cloc.js.map