/**
 * End-to-end tests for the `ai-governance discover` subcommand.
 *
 * Exercises the binary the way a customer would — by spawning a real
 * node/tsx process and asserting on exit code + stdout/stderr. This is
 * the customer-code-path probe that satisfies Evidence-First Protocol
 * Rule 3 (real running service, not mocks).
 *
 * @connexum/ai-governance  CLI integration tests
 */
import { describe, it } from 'node:test';
import * as assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import * as crypto from 'node:crypto';
const CLI = path.join(__dirname, 'index.ts');
// `__dirname` is undefined in ESM but the test runner here is CJS-mode tsx.
// Fall back to a resolved path against the repo root if needed.
const RESOLVED_CLI = fs.existsSync(CLI)
    ? CLI
    : path.resolve(process.cwd(), 'src/cli/index.ts');
function runCli(args) {
    const res = spawnSync('npx', ['-y', 'tsx', RESOLVED_CLI, ...args], {
        encoding: 'utf8',
        env: { ...process.env, NODE_OPTIONS: '' },
    });
    return {
        code: res.status ?? -1,
        stdout: res.stdout ?? '',
        stderr: res.stderr ?? '',
    };
}
function makeProject(files) {
    const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-disc-'));
    for (const [rel, content] of Object.entries(files)) {
        const full = path.join(dir, rel);
        fs.mkdirSync(path.dirname(full), { recursive: true });
        fs.writeFileSync(full, content);
    }
    return dir;
}
function writeKeyPem(dir) {
    const { privateKey } = crypto.generateKeyPairSync('ed25519');
    const pem = privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();
    const keyPath = path.join(dir, 'org-private.pem');
    fs.writeFileSync(keyPath, pem);
    return keyPath;
}
describe('ai-governance discover (real CLI invocation)', () => {
    it('--help prints usage and exits 0', () => {
        const r = runCli(['discover', '--help']);
        assert.equal(r.code, 0);
        assert.match(r.stdout, /Scan a project for agents/i);
        assert.match(r.stdout, /--root/);
        assert.match(r.stdout, /--org-id/);
        assert.match(r.stdout, /--key/);
    });
    it('missing --root prints error and exits 2', () => {
        const r = runCli(['discover', '--org-id', 'org-x']);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /--root is required/);
    });
    it('missing --org-id prints error and exits 2', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const r = runCli(['discover', '--root', root]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /--org-id is required/);
    });
    it('unknown flag exits 2', () => {
        const r = runCli(['discover', '--root', '/tmp', '--bogus-flag']);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /unknown flag/);
    });
    it('dry-run with two agents prints a report and exits 0', () => {
        const root = makeProject({
            '.claude/agents/a.md': `---\nname: a\ntools: Bash, Read\n---`,
            '.claude/agents/b.md': `---\nname: b\ntools: WebFetch\n---`,
        });
        const r = runCli(['discover', '--root', root, '--org-id', 'org-x', '--dry-run']);
        assert.equal(r.code, 0, `expected exit 0, got ${r.code}. stderr=${r.stderr}`);
        assert.match(r.stdout, /Found 2 agents/);
        assert.match(r.stdout, /\[DRY-RUN\]/);
        assert.match(r.stdout, /claude-code:a/);
        assert.match(r.stdout, /claude-code:b/);
    });
    it('non-dry-run without --key exits 2', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const r = runCli([
            'discover', '--root', root, '--org-id', 'org-x',
            '--endpoint', 'https://example.test/api/v1/manifests',
        ]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /--key is required/);
    });
    it('non-dry-run without --endpoint exits 2', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const keyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-key-'));
        const keyPath = writeKeyPem(keyDir);
        const r = runCli([
            'discover', '--root', root, '--org-id', 'org-x', '--key', keyPath,
        ]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /--endpoint is required/);
    });
    it('invalid PEM file exits 2 with structured error', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const badKey = path.join(root, 'bad.pem');
        fs.writeFileSync(badKey, 'not a real PEM');
        const r = runCli([
            'discover', '--root', root, '--org-id', 'org-x',
            '--key', badKey, '--endpoint', 'https://example.test/api/v1/manifests',
        ]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /invalid PEM private key/);
    });
    it('missing --key file exits 2', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const r = runCli([
            'discover', '--root', root, '--org-id', 'org-x',
            '--key', '/tmp/does-not-exist-' + Date.now(), '--endpoint', 'https://example.test/api/v1/manifests',
        ]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /cannot read --key/);
    });
    it('empty project + dry-run prints "Found 0 agents" and exits 0', () => {
        const root = makeProject({ 'README.md': '# empty' });
        const r = runCli(['discover', '--root', root, '--org-id', 'org-x', '--dry-run']);
        assert.equal(r.code, 0);
        assert.match(r.stdout, /Found 0 agents/);
    });
    it('--max-depth=2 hides deeper agents', () => {
        const root = makeProject({
            'a/b/c/d/agent.md': `---\nname: deep\ntools: Bash\n---`,
        });
        const shallow = runCli([
            'discover', '--root', root, '--org-id', 'org-x', '--dry-run',
            '--max-depth', '2',
        ]);
        assert.equal(shallow.code, 0);
        assert.match(shallow.stdout, /Found 0 agents/);
        const deep = runCli([
            'discover', '--root', root, '--org-id', 'org-x', '--dry-run',
            '--max-depth', '10',
        ]);
        assert.equal(deep.code, 0);
        assert.match(deep.stdout, /Found 1 agent/);
    });
    it('integrates with existing CLI dispatch (`--help` still works at root)', () => {
        const r = runCli(['--help']);
        assert.equal(r.code, 0);
        assert.match(r.stdout, /ai-governance discover/);
        assert.match(r.stdout, /Scan project \+ push signed manifests/);
    });
});
//# sourceMappingURL=discover.test.js.map