"use strict";
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 });
const child_process_1 = require("child_process");
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const CLI = path.join(process.cwd(), 'dist', 'index.js');
function getHelp(args = []) {
    const r = (0, child_process_1.spawnSync)('node', [CLI, ...args, '--help'], { encoding: 'utf-8', timeout: 15000 });
    return (r.stdout || '') + (r.stderr || '');
}
function assertCommandExists(args, label) {
    const r = (0, child_process_1.spawnSync)('node', [CLI, ...args, '--help'], { encoding: 'utf-8', timeout: 15000 });
    if (r.status !== 0) {
        throw new Error(`MISSING_COMMAND[${label}]: \`openlife ${args.join(' ')}\` returned exit ${r.status}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`);
    }
}
const rootHelp = getHelp();
const requiredTopLevel = ['agents', 'governance', 'install', 'start', 'status', 'agent'];
for (const cmd of requiredTopLevel) {
    if (!new RegExp(`(^|\\s)${cmd}\\b`, 'm').test(rootHelp)) {
        throw new Error(`MISSING_TOP_LEVEL_COMMAND: "${cmd}" not present in root --help output`);
    }
}
assertCommandExists(['agents'], 'agents-group');
const agentsHelp = getHelp(['agents']);
for (const sub of ['list', 'create', 'show']) {
    if (!new RegExp(`\\b${sub}\\b`).test(agentsHelp)) {
        throw new Error(`MISSING_SUBCOMMAND[agents ${sub}]: not in agents --help`);
    }
}
const governanceHelp = getHelp(['governance']);
for (const sub of ['status', 'audit', 'risk-check', 'consent', 'policy']) {
    if (!new RegExp(`\\b${sub}\\b`).test(governanceHelp)) {
        throw new Error(`MISSING_SUBCOMMAND[governance ${sub}]: not in governance --help`);
    }
}
const policyHelp = getHelp(['governance', 'policy']);
if (!/\bshow\b/.test(policyHelp))
    throw new Error('MISSING_SUBCOMMAND[governance policy show]');
const tmpAgentDir = path.join(process.cwd(), '.catalog', 'agents', 'test-cli-doc-parity-agent');
const tmpAgentFile = path.join(tmpAgentDir, 'AGENT.md');
fs.mkdirSync(tmpAgentDir, { recursive: true });
fs.writeFileSync(tmpAgentFile, `---\nid: test-cli-doc-parity-agent\nrole: tester\nstatus: draft\n---\n\n# test-cli-doc-parity-agent\n\n## Capabilities\n- routing\n- diagnostics\n`, 'utf-8');
try {
    const showRes = (0, child_process_1.spawnSync)('node', [CLI, 'agents', 'show', 'test-cli-doc-parity-agent'], { encoding: 'utf-8', timeout: 15000 });
    if (showRes.status !== 0) {
        throw new Error(`AGENTS_SHOW_EXIT_${showRes.status}\nstdout: ${showRes.stdout}\nstderr: ${showRes.stderr}`);
    }
    let parsed;
    try {
        parsed = JSON.parse(showRes.stdout);
    }
    catch {
        throw new Error(`AGENTS_SHOW_NOT_JSON: ${showRes.stdout.slice(0, 200)}`);
    }
    if (!parsed.ok || parsed.id !== 'test-cli-doc-parity-agent')
        throw new Error(`AGENTS_SHOW_WRONG_PAYLOAD: ${JSON.stringify(parsed)}`);
    if (!Array.isArray(parsed.capabilities) || parsed.capabilities.length !== 2) {
        throw new Error(`AGENTS_SHOW_CAPABILITIES_NOT_PARSED: ${JSON.stringify(parsed.capabilities)}`);
    }
    const missingRes = (0, child_process_1.spawnSync)('node', [CLI, 'agents', 'show', 'definitely-does-not-exist-xyz'], { encoding: 'utf-8', timeout: 15000 });
    if (missingRes.status === 0)
        throw new Error('AGENTS_SHOW_SHOULD_FAIL_FOR_MISSING_ID');
    if (!/agent_not_found/.test(missingRes.stdout))
        throw new Error(`AGENTS_SHOW_MISSING_PAYLOAD: ${missingRes.stdout}`);
    const policyShowRes = (0, child_process_1.spawnSync)('node', [CLI, 'governance', 'policy', 'show'], { encoding: 'utf-8', timeout: 15000 });
    let policyPayload;
    try {
        policyPayload = JSON.parse(policyShowRes.stdout);
    }
    catch {
        throw new Error(`POLICY_SHOW_NOT_JSON: ${policyShowRes.stdout.slice(0, 200)}`);
    }
    if (typeof policyPayload.ok !== 'boolean')
        throw new Error(`POLICY_SHOW_NO_OK_FIELD`);
}
finally {
    fs.rmSync(tmpAgentDir, { recursive: true, force: true });
}
const installDocs = ['INSTALL.md', 'README.md'].filter((f) => fs.existsSync(path.join(process.cwd(), f)));
const documentedVerbs = new Set();
for (const doc of installDocs) {
    const raw = fs.readFileSync(path.join(process.cwd(), doc), 'utf-8');
    const matches = raw.matchAll(/\bopenlife\s+(agent|agents|install|start|status|governance|system)\b/g);
    for (const m of matches)
        documentedVerbs.add(m[1]);
}
for (const v of documentedVerbs) {
    if (!new RegExp(`\\b${v}\\b`).test(rootHelp)) {
        throw new Error(`DOC_DRIFT: docs reference "openlife ${v}" but root --help has no such command`);
    }
}
console.log(`TEST_CLI_DOC_PARITY_OK (top-level=${requiredTopLevel.length}, docs-checked=${installDocs.join(',')}, doc-verbs=${[...documentedVerbs].join('|')})`);
