/**
 * RED-GREEN tests for the discovery CLI runner.
 *
 * @connexum/ai-governance  discovery-cli (W2.1 + push transport binary)
 */
import { describe, it } from 'node:test';
import * as assert from 'node:assert/strict';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { runDiscoveryCli, formatCliReport } from './discovery-cli.js';
import { generateOrgKeyPair } from './signed-manifest.js';
function makeProject(files) {
    const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'disc-cli-'));
    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 recordingTransport() {
    const calls = [];
    return {
        calls,
        transport: async (req) => {
            calls.push(req);
            return { status: 201, bodyText: `{"id":"r_${calls.length}"}` };
        },
    };
}
const noopSleep = async (_ms) => undefined;
describe('discovery CLI runner', () => {
    it('discovers + signs + pushes manifests in one call', async () => {
        const root = makeProject({
            '.claude/agents/a.md': `---\nname: a\ntools: Bash, Read\n---`,
            '.claude/agents/b.md': `---\nname: b\ntools: WebFetch\n---`,
        });
        const t = recordingTransport();
        const { privateKey } = generateOrgKeyPair();
        const result = await runDiscoveryCli({
            rootDir: root,
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
        });
        assert.equal(result.ok, true);
        assert.equal(result.agentCount, 2);
        assert.equal(result.successCount, 2);
        assert.equal(result.failureCount, 0);
        assert.equal(t.calls.length, 2);
        assert.equal(t.calls[0].headers['x-connexum-org'], 'org-x');
    });
    it('dryRun: returns manifests with push=null and skips network', async () => {
        const root = makeProject({
            '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---`,
        });
        const t = recordingTransport();
        const { privateKey } = generateOrgKeyPair();
        const result = await runDiscoveryCli({
            rootDir: root,
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
            dryRun: true,
        });
        assert.equal(result.agentCount, 1);
        assert.equal(result.reports[0].push, null);
        assert.equal(t.calls.length, 0);
        assert.equal(result.ok, true);
    });
    it('failure on one manifest is reported but does not stop other pushes', async () => {
        const root = makeProject({
            '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---`,
            '.claude/agents/b.md': `---\nname: b\ntools: Read\n---`,
            '.claude/agents/c.md': `---\nname: c\ntools: Write\n---`,
        });
        let i = 0;
        const transport = async () => {
            i++;
            if (i === 2)
                return { status: 400, bodyText: '{"error":"bad"}' };
            return { status: 201, bodyText: `{"id":"r_${i}"}` };
        };
        const { privateKey } = generateOrgKeyPair();
        const result = await runDiscoveryCli({
            rootDir: root,
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport,
            sleep: noopSleep,
        });
        assert.equal(result.agentCount, 3);
        assert.equal(result.successCount, 2);
        assert.equal(result.failureCount, 1);
        assert.equal(result.ok, false);
    });
    it('zero agents discovered -> ok=true with 0 counts', async () => {
        const root = makeProject({ 'README.md': '# empty' });
        const t = recordingTransport();
        const { privateKey } = generateOrgKeyPair();
        const result = await runDiscoveryCli({
            rootDir: root,
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
        });
        assert.equal(result.agentCount, 0);
        assert.equal(result.ok, true);
        assert.equal(t.calls.length, 0);
    });
    it('missing rootDir / orgId / endpoint throws (fail-closed)', async () => {
        const { privateKey } = generateOrgKeyPair();
        await assert.rejects(runDiscoveryCli({ rootDir: '', orgId: 'o', privateKey, endpoint: 'https://x' }), /rootDir is required/);
        await assert.rejects(runDiscoveryCli({ rootDir: '/tmp', orgId: '', privateKey, endpoint: 'https://x' }), /orgId is required/);
        await assert.rejects(runDiscoveryCli({ rootDir: '/tmp', orgId: 'o', privateKey, endpoint: '' }), /endpoint is required/);
    });
    it('formatCliReport produces readable summary text', async () => {
        const root = makeProject({
            '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---`,
        });
        const t = recordingTransport();
        const { privateKey } = generateOrgKeyPair();
        const result = await runDiscoveryCli({
            rootDir: root,
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
        });
        const text = formatCliReport(result);
        assert.match(text, /Connexum Discovery/);
        assert.match(text, /Found 1 agent/);
        assert.match(text, /\[OK\]/);
        assert.match(text, /receipt=r_1/);
    });
    it('formatCliReport in dryRun mode shows [DRY-RUN] for every agent', async () => {
        const root = makeProject({
            '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---`,
            '.claude/agents/b.md': `---\nname: b\ntools: Read\n---`,
        });
        const { privateKey } = generateOrgKeyPair();
        const result = await runDiscoveryCli({
            rootDir: root,
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            sleep: noopSleep,
            dryRun: true,
        });
        const text = formatCliReport(result);
        const matches = text.match(/\[DRY-RUN\]/g) ?? [];
        assert.equal(matches.length, 2);
    });
    it('respects discovery options (maxDepth)', async () => {
        const root = makeProject({
            'a/b/c/d/agent.md': `---\nname: deep\ntools: Bash\n---`,
        });
        const t = recordingTransport();
        const { privateKey } = generateOrgKeyPair();
        const shallow = await runDiscoveryCli({
            rootDir: root,
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
            discovery: { maxDepth: 2 },
        });
        assert.equal(shallow.agentCount, 0);
        const deep = await runDiscoveryCli({
            rootDir: root,
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
            discovery: { maxDepth: 10 },
        });
        assert.equal(deep.agentCount, 1);
    });
});
//# sourceMappingURL=discovery-cli.test.js.map