/**
 * RED-GREEN tests for F-NEW-PRODUCT-AGENT-DISCOVERY-CLI (W2.1).
 *
 * @connexum/ai-governance  F-NEW-PRODUCT-AGENT-DISCOVERY-CLI
 */
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 { discoverAgents } from './agent-discovery.js';
function makeProject(files) {
    const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-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;
}
describe('F-NEW-PRODUCT-AGENT-DISCOVERY-CLI (W2.1)', () => {
    it('detects Claude Code agent.md with frontmatter tools', () => {
        const root = makeProject({
            '.claude/agents/mailer.md': `---
name: mailer
tools: Read, Write, Bash, WebFetch
---

You are a mailer agent.
`,
        });
        const manifests = discoverAgents(root);
        assert.equal(manifests.length, 1);
        assert.equal(manifests[0].agentId, 'claude-code:mailer');
        assert.deepEqual(manifests[0].tools, ['Read', 'Write', 'Bash', 'WebFetch']);
        assert.equal(manifests[0].llmProvider, 'anthropic/claude-code');
    });
    it('detects multiple agent.md files at different depths', () => {
        const root = makeProject({
            '.claude/agents/a.md': `---\nname: a\ntools: Read\n---\nA agent`,
            'subfolder/.claude/agents/b.md': `---\nname: b\ntools: Write, Bash\n---\nB agent`,
        });
        const manifests = discoverAgents(root);
        assert.equal(manifests.length, 2);
        const ids = manifests.map((m) => m.agentId).sort();
        assert.deepEqual(ids, ['claude-code:a', 'claude-code:b']);
    });
    it('detects OpenAI Agents SDK new Agent({}) instantiations in TS', () => {
        const root = makeProject({
            'src/agent.ts': `
        import { Agent } from '@openai/agents';
        const myAgent = new Agent({
          name: 'researcher',
          tools: [webSearch, summarize, db_query],
        });
      `,
        });
        const manifests = discoverAgents(root);
        const oa = manifests.find((m) => m.agentId.startsWith('openai-agents:'));
        assert.ok(oa, 'OpenAI agent detected');
        assert.equal(oa?.name, 'researcher');
        assert.ok(oa?.tools.includes('webSearch'));
        assert.ok(oa?.tools.includes('db_query'));
    });
    it('detects LangChain Tool / DynamicTool registrations', () => {
        const root = makeProject({
            'src/tools.js': `
        const t1 = new DynamicTool({ name: 'searchTool', description: 'search the web' });
        const t2 = new Tool({ name: 'computeTool', description: 'compute' });
      `,
        });
        const manifests = discoverAgents(root);
        const lc = manifests.find((m) => m.agentId.startsWith('langchain:'));
        assert.ok(lc, 'LangChain agent detected');
        assert.deepEqual(lc?.tools.sort(), ['computeTool', 'searchTool']);
    });
    it('detects MCP servers from mcp.json', () => {
        const root = makeProject({
            'mcp.json': JSON.stringify({
                mcpServers: {
                    github: { command: 'mcp-server-github' },
                    postgres: { url: 'https://internal.example/mcp' },
                },
            }, null, 2),
        });
        const manifests = discoverAgents(root);
        const mcp = manifests.find((m) => m.agentId.startsWith('mcp-config:'));
        assert.ok(mcp, 'MCP agent detected');
        assert.deepEqual(mcp?.tools.sort(), ['mcp__github', 'mcp__postgres']);
        assert.equal(mcp?.mcpServers?.length, 2);
    });
    it('skips node_modules and other skip-dirs', () => {
        const root = makeProject({
            'node_modules/some-pkg/.claude/agents/should-skip.md': `---\nname: skipme\ntools: x\n---`,
            'src/.claude/agents/real.md': `---\nname: real\ntools: Read\n---`,
        });
        const manifests = discoverAgents(root);
        assert.equal(manifests.length, 1);
        assert.equal(manifests[0].agentId, 'claude-code:real');
    });
    it('respects maxDepth option', () => {
        const root = makeProject({
            'a/b/c/d/e/agent.md': `---\nname: deep\ntools: x\n---`,
        });
        const manifests = discoverAgents(root, { maxDepth: 2 });
        assert.equal(manifests.length, 0, 'agent at depth 5 should be ignored when maxDepth=2');
        const manifestsDeep = discoverAgents(root, { maxDepth: 10 });
        assert.equal(manifestsDeep.length, 1);
    });
    it('returns empty array on a directory with no agents', () => {
        const root = makeProject({
            'README.md': '# nothing here',
            'src/index.ts': 'export const x = 1;',
        });
        const manifests = discoverAgents(root);
        assert.deepEqual(manifests, []);
    });
    it('throws on missing root directory (fail-closed)', () => {
        assert.throws(() => discoverAgents('/tmp/this-does-not-exist-' + Date.now()), /does not exist/);
    });
    it('throws when root is a file, not a directory (fail-closed)', () => {
        const root = makeProject({ 'file.md': 'content' });
        assert.throws(() => discoverAgents(path.join(root, 'file.md')), /not a directory/);
    });
    it('manifests are deduplicated by agentId', () => {
        const root = makeProject({
            '.claude/agents/dup.md': `---\nname: dup\ntools: x\n---`,
            'other/.claude/agents/dup.md': `---\nname: dup\ntools: y\n---`,
        });
        const manifests = discoverAgents(root);
        assert.equal(manifests.length, 1, 'duplicate agentId removed');
    });
    it('detection output is shape-compatible with autoGenerateCompanyPack', async () => {
        const root = makeProject({
            'src/agent.ts': `new Agent({ name: 'pay-bot', tools: [bash, postgresQuery] })`,
        });
        const [manifest] = discoverAgents(root);
        const { autoGenerateCompanyPack } = await import('./auto-pack-generator.js');
        const result = autoGenerateCompanyPack(manifest, { acceptAllSuggestedRules: true });
        assert.ok(result.pack.id.length > 0);
        assert.equal(result.acceptedRules.length, result.proposedRules.length);
    });
});
//# sourceMappingURL=agent-discovery.test.js.map