import fs from 'node:fs';
import path from 'node:path';
import { parse as parseYaml } from 'yaml';
function findSquadDir(squadsDir, code) {
    if (!fs.existsSync(squadsDir))
        return null;
    const matches = [];
    function walk(dir, depth) {
        if (depth > 4)
            return;
        const yamlPath = path.join(dir, 'squad.yaml');
        if (fs.existsSync(yamlPath)) {
            try {
                const raw = fs.readFileSync(yamlPath, 'utf-8');
                const parsed = parseYaml(raw);
                if (parsed?.squad?.code === code)
                    matches.push(dir);
            }
            catch { /* skip */ }
            return;
        }
        let entries;
        try {
            entries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const entry of entries) {
            if (!entry.isDirectory())
                continue;
            if (entry.name.startsWith('.') || entry.name.startsWith('_'))
                continue;
            walk(path.join(dir, entry.name), depth + 1);
        }
    }
    walk(squadsDir, 0);
    return matches[0] ?? null;
}
function discoverSquads(squadsDir) {
    if (!fs.existsSync(squadsDir))
        return [];
    const squads = [];
    function walk(dir, depth) {
        if (depth > 4)
            return;
        let entries;
        try {
            entries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const entry of entries) {
            if (!entry.isDirectory())
                continue;
            if (entry.name.startsWith('.') || entry.name.startsWith('_'))
                continue;
            const fullPath = path.join(dir, entry.name);
            const yamlPath = path.join(fullPath, 'squad.yaml');
            if (fs.existsSync(yamlPath)) {
                // Squad directory — parse and push, don't recurse further
                try {
                    const raw = fs.readFileSync(yamlPath, 'utf-8');
                    const parsed = parseYaml(raw);
                    const s = parsed?.squad;
                    if (s) {
                        const rawSteps = s.pipeline?.steps;
                        const steps = Array.isArray(rawSteps)
                            ? rawSteps.map((st) => ({
                                id: st.id || '',
                                agent: st.agent || '',
                                label: st.label || '',
                                ...(st.deliverFrom ? { deliverFrom: st.deliverFrom } : {}),
                            }))
                            : [];
                        squads.push({
                            code: typeof s.code === 'string' ? s.code : entry.name,
                            ...(typeof s.setor === 'string' ? { setor: s.setor } : {}),
                            ...(typeof s.grupo === 'string' ? { grupo: s.grupo } : {}),
                            ...(typeof s.sessao === 'string' ? { sessao: s.sessao } : {}),
                            ...(typeof s.group === 'string' ? { group: s.group } : {}),
                            name: typeof s.name === 'string' ? s.name : entry.name,
                            description: typeof s.description === 'string' ? s.description : '',
                            icon: typeof s.icon === 'string' ? s.icon : '📋',
                            agents: Array.isArray(s.agents)
                                ? s.agents.map((a) => ({
                                    id: a.id || a,
                                    name: a.name || a.id || a,
                                    icon: a.icon || 'robot',
                                    ...(a.avatar ? { avatar: a.avatar } : {}),
                                }))
                                : [],
                            pipeline: { steps },
                        });
                    }
                }
                catch {
                    squads.push({
                        code: entry.name,
                        name: entry.name,
                        description: '',
                        icon: '📋',
                        agents: [],
                        pipeline: { steps: [] },
                    });
                }
                // Do NOT recurse into squad dirs
            }
            else {
                // Not a squad dir — recurse to find nested squads
                walk(fullPath, depth + 1);
            }
        }
    }
    walk(squadsDir, 0);
    return squads;
}
export async function squadsRoutes(app, opts) {
    const { squadsDir } = opts;
    // GET /api/squads
    app.get('/api/squads', { preHandler: [app.requireAuth] }, async () => {
        return { squads: discoverSquads(squadsDir) };
    });
    // GET /api/squads/:name
    app.get('/api/squads/:name', { preHandler: [app.requireAuth] }, async (request, reply) => {
        const { name } = request.params;
        const squadDir = findSquadDir(squadsDir, name);
        if (!squadDir) {
            return reply.code(404).send({ error: 'Squad not found' });
        }
        const squads = discoverSquads(squadsDir);
        const squad = squads.find((s) => s.code === name);
        let state = null;
        const statePath = path.join(squadDir, 'state.json');
        if (fs.existsSync(statePath)) {
            try {
                state = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
            }
            catch {
                // Skip invalid JSON
            }
        }
        return { squad: squad || { code: name, name, description: '', icon: '📋', agents: [], pipeline: { steps: [] } }, state };
    });
    // GET /api/squads/:name/state
    app.get('/api/squads/:name/state', { preHandler: [app.requireAuth] }, async (request, reply) => {
        const { name } = request.params;
        const squadDir = findSquadDir(squadsDir, name);
        if (!squadDir) {
            return reply.code(404).send({ error: 'Squad not found' });
        }
        const statePath = path.join(squadDir, 'state.json');
        if (!fs.existsSync(statePath)) {
            return reply.code(404).send({ error: 'State not found' });
        }
        try {
            return JSON.parse(fs.readFileSync(statePath, 'utf-8'));
        }
        catch {
            return reply.code(500).send({ error: 'Invalid state file' });
        }
    });
}
//# sourceMappingURL=squads-routes.js.map