import fs from 'node:fs';
import path from 'node:path';
import { parse as parseYaml } from 'yaml';
function loadCatalog(squadsDir) {
    const catalogPath = path.resolve(squadsDir, '..', 'agents', '_catalog.yaml');
    if (!fs.existsSync(catalogPath))
        return [];
    try {
        const raw = fs.readFileSync(catalogPath, 'utf-8');
        const parsed = parseYaml(raw);
        return parsed?.catalog?.sectors || [];
    }
    catch {
        return [];
    }
}
function loadSquads(squadsDir) {
    if (!fs.existsSync(squadsDir))
        return [];
    const entries = fs.readdirSync(squadsDir, { withFileTypes: true });
    const squads = [];
    for (const entry of entries) {
        if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_'))
            continue;
        const yamlPath = path.join(squadsDir, entry.name, 'squad.yaml');
        if (!fs.existsSync(yamlPath))
            continue;
        try {
            const raw = fs.readFileSync(yamlPath, 'utf-8');
            const parsed = parseYaml(raw);
            const s = parsed?.squad;
            if (s) {
                const steps = [];
                if (s.pipeline?.steps) {
                    for (const step of s.pipeline.steps) {
                        steps.push({
                            id: step.id,
                            agent: step.agent || undefined,
                            label: step.label || '',
                            type: step.type || undefined,
                            deliverFrom: step.deliverFrom || undefined,
                        });
                    }
                }
                squads.push({
                    code: s.code || entry.name,
                    name: s.name || entry.name,
                    description: s.description || '',
                    icon: s.icon || 'folder',
                    agents: Array.isArray(s.agents)
                        ? s.agents.map((a) => ({ id: a.id || a, name: a.name || a.id || a, icon: a.icon || 'robot' }))
                        : [],
                    pipeline: steps,
                });
            }
        }
        catch { /* skip */ }
    }
    return squads;
}
function loadCompanyName(squadsDir) {
    const companyPath = path.resolve(squadsDir, '..', '_expxagents', '_memory', 'company.md');
    if (!fs.existsSync(companyPath))
        return 'Company';
    try {
        const content = fs.readFileSync(companyPath, 'utf-8');
        const nameMatch = content.match(/(?:^|\n)#\s+(.+)/);
        if (nameMatch)
            return nameMatch[1].trim();
        const fieldMatch = content.match(/company_name:\s*(.+)/i);
        if (fieldMatch)
            return fieldMatch[1].trim();
    }
    catch { /* ignore */ }
    return 'Company';
}
function buildOrgChart(squadsDir) {
    const sectors = loadCatalog(squadsDir);
    const squads = loadSquads(squadsDir);
    const companyName = loadCompanyName(squadsDir);
    // Build agent → squads map
    const agentSquadMap = new Map();
    for (const squad of squads) {
        for (const agent of squad.agents) {
            const existing = agentSquadMap.get(agent.id) || [];
            existing.push(squad.name);
            agentSquadMap.set(agent.id, existing);
        }
    }
    const sectorNodes = sectors.map((sector) => ({
        id: sector.name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
        name: sector.name,
        type: 'sector',
        agentCount: sector.agents.length,
        children: sector.agents.map((agentId) => ({
            id: agentId,
            name: agentId.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),
            type: 'agent',
            squads: agentSquadMap.get(agentId) || [],
        })),
    }));
    const tree = {
        id: 'company',
        name: companyName,
        type: 'company',
        children: sectorNodes,
    };
    return { tree, squads };
}
export async function orgchartRoutes(app, opts) {
    app.get('/api/orgchart', { preHandler: [app.requireAuth] }, async () => {
        return buildOrgChart(opts.squadsDir);
    });
}
//# sourceMappingURL=orgchart-routes.js.map