#!/usr/bin/env node
"use strict";
/**
 * Agent Registry Builder
 * Scans all agents and generates a registry JSON file for fast lookups
 */
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.buildRegistry = buildRegistry;
exports.saveRegistry = saveRegistry;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
function parseFrontmatter(content) {
    const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
    if (!frontmatterMatch)
        return null;
    const lines = frontmatterMatch[1].split('\n');
    const frontmatter = {};
    for (const line of lines) {
        const match = line.match(/^(\w+):\s*(.*)$/);
        if (match) {
            frontmatter[match[1]] = match[2].trim();
        }
    }
    return frontmatter;
}
function scanAgents(agentsDir) {
    const agents = [];
    function scanDir(dir, dept) {
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        for (const entry of entries) {
            const fullPath = path.join(dir, entry.name);
            const relativePath = path.relative(agentsDir, fullPath);
            if (entry.isDirectory()) {
                scanDir(fullPath, entry.name);
            }
            else if (entry.name.endsWith('.md')) {
                const content = fs.readFileSync(fullPath, 'utf-8');
                const frontmatter = parseFrontmatter(content);
                if (frontmatter) {
                    const stats = fs.statSync(fullPath);
                    const agentName = entry.name.replace('.md', '');
                    agents.push({
                        id: `@${agentName}`,
                        name: frontmatter.name || agentName,
                        description: frontmatter.description || '',
                        department: dept,
                        filePath: relativePath,
                        color: frontmatter.color,
                        emoji: frontmatter.emoji,
                        vibe: frontmatter.vibe,
                        lastModified: stats.mtime.toISOString()
                    });
                }
            }
        }
    }
    scanDir(agentsDir, 'root');
    return agents;
}
function loadKeywords(routerDir) {
    const keywordsPath = path.join(routerDir, 'keywords.json');
    if (!fs.existsSync(keywordsPath)) {
        return {};
    }
    const content = fs.readFileSync(keywordsPath, 'utf-8');
    const data = JSON.parse(content);
    const keywords = {};
    for (const [agentId, config] of Object.entries(data.agents || {})) {
        const agentConfig = config;
        keywords[agentId] = agentConfig.keywords || [];
    }
    return keywords;
}
function buildRegistry() {
    const agentsDir = path.join(process.cwd(), 'agents');
    const routerDir = path.join(process.cwd(), 'router');
    if (!fs.existsSync(agentsDir)) {
        throw new Error(`Agents directory not found: ${agentsDir}`);
    }
    console.log('🔍 Scanning agents...');
    const agents = scanAgents(agentsDir);
    console.log(`✅ Found ${agents.length} agents`);
    // Group by department
    const departments = {};
    const agentsById = {};
    for (const agent of agents) {
        if (!departments[agent.department]) {
            departments[agent.department] = [];
        }
        departments[agent.department].push(agent);
        agentsById[agent.id] = agent;
    }
    // Load keywords
    const keywords = loadKeywords(routerDir);
    return {
        generatedAt: new Date().toISOString(),
        totalAgents: agents.length,
        departments,
        agentsById,
        keywords
    };
}
function saveRegistry(registry) {
    const registryPath = path.join(process.cwd(), 'router', 'agent-registry.json');
    fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2));
    console.log(`📝 Registry saved to ${registryPath}`);
}
function printStats(registry) {
    console.log('\n📊 Agent Registry Statistics:');
    console.log(`   Total Agents: ${registry.totalAgents}`);
    console.log(`   Departments: ${Object.keys(registry.departments).length}`);
    console.log('\n   By Department:');
    for (const [dept, agents] of Object.entries(registry.departments)) {
        if (dept !== 'root') {
            console.log(`     ${dept}: ${agents.length} agents`);
        }
    }
    // Check for agents without keywords
    const agentsWithoutKeywords = Object.keys(registry.agentsById).filter(id => !registry.keywords[id]);
    if (agentsWithoutKeywords.length > 0) {
        console.log(`\n⚠️  ${agentsWithoutKeywords.length} agents without keywords in router/keywords.json`);
        console.log('   Run: opencode-agency sync-keywords');
    }
}
// Main
if (require.main === module) {
    try {
        const registry = buildRegistry();
        saveRegistry(registry);
        printStats(registry);
        process.exit(0);
    }
    catch (error) {
        console.error('❌ Error building registry:', error);
        process.exit(1);
    }
}
//# sourceMappingURL=build-registry.js.map