"use strict";
/**
 * Agent Loader
 * Loads and parses agent markdown files from global install
 */
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.AgentLoader = void 0;
exports.getGlobalAgentsPath = getGlobalAgentsPath;
exports.hasGlobalAgents = hasGlobalAgents;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class AgentLoader {
    agentsPath;
    constructor(agentsPath) {
        this.agentsPath = agentsPath;
    }
    /**
     * Parse frontmatter from markdown content
     */
    parseFrontmatter(content) {
        const match = content.match(/^---\n([\s\S]*?)\n---/);
        if (!match)
            return null;
        const lines = match[1].split('\n');
        const frontmatter = {};
        for (const line of lines) {
            const kv = line.match(/^(\w+):\s*(.*)$/);
            if (kv) {
                frontmatter[kv[1]] = kv[2].trim();
            }
        }
        return frontmatter;
    }
    /**
     * Scan directory for agent files
     */
    scanDirectory(dir, dept) {
        const agents = [];
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        for (const entry of entries) {
            const fullPath = path.join(dir, entry.name);
            if (entry.isDirectory()) {
                // Recurse into subdirectories
                agents.push(...this.scanDirectory(fullPath, entry.name));
            }
            else if (entry.name.endsWith('.md')) {
                try {
                    const content = fs.readFileSync(fullPath, 'utf-8');
                    const frontmatter = this.parseFrontmatter(content);
                    if (frontmatter) {
                        const stats = fs.statSync(fullPath);
                        const agentName = entry.name.replace('.md', '');
                        const relativePath = path.relative(this.agentsPath, fullPath);
                        agents.push({
                            id: `@${agentName}`,
                            name: frontmatter.name || agentName,
                            description: frontmatter.description || '',
                            department: dept,
                            filePath: relativePath,
                            frontmatter,
                            content,
                            color: frontmatter.color,
                            emoji: frontmatter.emoji,
                            vibe: frontmatter.vibe,
                            lastModified: stats.mtime
                        });
                    }
                }
                catch (error) {
                    console.warn(`Warning: Failed to parse agent ${fullPath}: ${error}`);
                }
            }
        }
        return agents;
    }
    /**
     * Build complete agent registry
     */
    async buildRegistry() {
        if (!fs.existsSync(this.agentsPath)) {
            throw new Error(`Agents directory not found: ${this.agentsPath}`);
        }
        const allAgents = this.scanDirectory(this.agentsPath, 'root');
        // Group by department
        const departments = {};
        const agents = {};
        for (const agent of allAgents) {
            if (!departments[agent.department]) {
                departments[agent.department] = [];
            }
            departments[agent.department].push(agent);
            agents[agent.id] = agent;
        }
        // Load keywords if available
        const keywordsPath = path.join(path.dirname(this.agentsPath), 'router', 'keywords.json');
        let keywords = {};
        let workflows = {};
        if (fs.existsSync(keywordsPath)) {
            try {
                const keywordsData = JSON.parse(fs.readFileSync(keywordsPath, 'utf-8'));
                keywords = keywordsData.agents || {};
                workflows = keywordsData.workflows || {};
            }
            catch {
                // Ignore keywords error
            }
        }
        return {
            generatedAt: new Date().toISOString(),
            totalAgents: allAgents.length,
            departments,
            agents,
            keywords,
            workflows
        };
    }
    /**
     * Load specific agent by ID
     */
    loadAgent(agentId) {
        const cleanId = agentId.startsWith('@') ? agentId.slice(1) : agentId;
        // Search for agent file
        const findAgentFile = (dir) => {
            const entries = fs.readdirSync(dir, { withFileTypes: true });
            for (const entry of entries) {
                const fullPath = path.join(dir, entry.name);
                if (entry.isDirectory()) {
                    const found = findAgentFile(fullPath);
                    if (found)
                        return found;
                }
                else if (entry.name === `${cleanId}.md`) {
                    return fullPath;
                }
            }
            return null;
        };
        const agentPath = findAgentFile(this.agentsPath);
        if (!agentPath)
            return null;
        try {
            const content = fs.readFileSync(agentPath, 'utf-8');
            const frontmatter = this.parseFrontmatter(content);
            if (!frontmatter)
                return null;
            const stats = fs.statSync(agentPath);
            const dept = path.relative(this.agentsPath, path.dirname(agentPath));
            return {
                id: `@${cleanId}`,
                name: frontmatter.name || cleanId,
                description: frontmatter.description || '',
                department: dept,
                filePath: path.relative(this.agentsPath, agentPath),
                frontmatter,
                content,
                color: frontmatter.color,
                emoji: frontmatter.emoji,
                vibe: frontmatter.vibe,
                lastModified: stats.mtime
            };
        }
        catch {
            return null;
        }
    }
    /**
     * Get agent system prompt
     */
    getAgentSystemPrompt(agent) {
        // Extract system prompt from agent content
        // Remove frontmatter, use remaining content
        const content = agent.content.replace(/^---\n[\s\S]*?\n---/, '').trim();
        return `You are ${agent.name}.

${agent.description}

${content}

Remember: Follow your Critical Rules. Stay in character. Execute tasks efficiently.`;
    }
}
exports.AgentLoader = AgentLoader;
/**
 * Get global agents path
 */
function getGlobalAgentsPath() {
    const homedir = require('os').homedir();
    return path.join(homedir, '.cli-brain', 'agents');
}
/**
 * Check if global agents exist
 */
function hasGlobalAgents() {
    try {
        const agentsPath = getGlobalAgentsPath();
        return require('fs').existsSync(agentsPath);
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=agent-loader.js.map