"use strict";
/**
 * doc_parity.ts — Story 7.2
 *
 * Reusable helpers for "documentation makes a claim about CLI surface — is it
 * still true?" tests. Used by:
 *   - test_cli_doc_parity.ts        (root help vs README quick-start)
 *   - test_multi_host_docs_parity.ts (per-host install docs vs CLI)
 *   - test_aiobuilder_cli_parity.ts (squad doc verbs vs aiobuilder sub-commands)
 *
 * Each helper is intentionally tiny. The goal is fewer copy-pasted regex
 * loops across parity tests, not an inheritance hierarchy.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.spawnCliHelp = spawnCliHelp;
exports.extractCommanderCommands = extractCommanderCommands;
exports.extractDocTokens = extractDocTokens;
exports.assertCliParity = assertCliParity;
const child_process_1 = require("child_process");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const CLI = path.join(process.cwd(), 'dist', 'index.js');
/** Spawn `node bin/openlife.js <args> --help` and return the merged stdout/stderr. */
function spawnCliHelp(args = [], timeoutMs = 20000) {
    const r = (0, child_process_1.spawnSync)('node', [CLI, ...args, '--help'], { encoding: 'utf-8', timeout: timeoutMs });
    return { ok: r.status === 0, status: r.status, help: (r.stdout || '') + (r.stderr || '') };
}
/**
 * Extract Commander sub-command names from a help block.
 * Commander prints each sub-command starting at column 2: "  <name> [options]...".
 */
function extractCommanderCommands(helpText) {
    const out = new Set();
    const lines = helpText.split('\n');
    let inCommands = false;
    for (const line of lines) {
        if (/^Commands:/.test(line)) {
            inCommands = true;
            continue;
        }
        if (!inCommands)
            continue;
        const m = line.match(/^\s{2}([a-z][\w-]*)/);
        if (m)
            out.add(m[1]);
    }
    return out;
}
/**
 * Read a doc file and extract every token matching `re` (must have one capture group).
 * Returns a sorted, de-duplicated list. Throws if the file does not exist.
 */
function extractDocTokens(docPath, re) {
    if (!fs.existsSync(docPath)) {
        throw new Error(`DOC_NOT_FOUND: ${docPath}`);
    }
    const content = fs.readFileSync(docPath, 'utf-8');
    const tokens = new Set();
    // Use matchAll to avoid stateful regex iteration.
    const reGlobal = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');
    for (const m of content.matchAll(reGlobal)) {
        if (m[1])
            tokens.add(m[1]);
    }
    return Array.from(tokens).sort();
}
/**
 * Assert every doc token corresponds to a CLI command (direct or via alias map).
 * Returns a verdict object — callers decide whether to throw, log, or annotate.
 */
function assertCliParity(docTokens, cliCommands, aliasMap = {}) {
    const matched = [];
    const missing = [];
    for (const tok of docTokens) {
        if (cliCommands.has(tok)) {
            matched.push({ token: tok, via: tok });
            continue;
        }
        const alias = aliasMap[tok];
        if (alias && cliCommands.has(alias)) {
            matched.push({ token: tok, via: `${alias} (alias)` });
            continue;
        }
        missing.push(tok);
    }
    return { ok: missing.length === 0, matched, missing, total: docTokens.length };
}
