import fs from 'node:fs';
import path from 'node:path';
function discoverFiles(squadsDir) {
    const entries = [];
    if (!fs.existsSync(squadsDir))
        return entries;
    for (const dir of fs.readdirSync(squadsDir, { withFileTypes: true })) {
        if (!dir.isDirectory() || dir.name.startsWith('.'))
            continue;
        const squadDir = path.join(squadsDir, dir.name);
        // Read squad name from squad.yaml
        let squadName = dir.name;
        const yamlPath = path.join(squadDir, 'squad.yaml');
        if (fs.existsSync(yamlPath)) {
            const content = fs.readFileSync(yamlPath, 'utf-8');
            const match = content.match(/^\s*name:\s*(.+)$/m);
            if (match)
                squadName = match[1].trim().replace(/^["']|["']$/g, '');
            entries.push({
                squad: dir.name,
                squadName,
                file: 'squad.yaml',
                label: 'Squad Config',
                path: 'squad.yaml',
            });
        }
        // Memory files
        const memDir = path.join(squadDir, '_memory');
        if (fs.existsSync(memDir) && fs.statSync(memDir).isDirectory()) {
            for (const memFile of fs.readdirSync(memDir)) {
                if (!memFile.endsWith('.md'))
                    continue;
                entries.push({
                    squad: dir.name,
                    squadName,
                    file: memFile,
                    label: memFile.replace('.md', '').replace(/-/g, ' '),
                    path: `_memory/${memFile}`,
                });
            }
        }
    }
    return entries;
}
export async function filesRoutes(app, opts) {
    const { squadsDir } = opts;
    // List all editable files
    app.get('/api/files', { preHandler: [app.requireAuth] }, async (_request, reply) => {
        const files = discoverFiles(squadsDir);
        return reply.send(files);
    });
    // Read a file
    app.get('/api/files/:squad/*', { preHandler: [app.requireAuth] }, async (request, reply) => {
        const { squad } = request.params;
        const filePath = request.params['*'];
        if (!filePath)
            return reply.status(400).send({ error: 'Missing file path' });
        // Prevent directory traversal
        const resolved = path.resolve(squadsDir, squad, filePath);
        if (!resolved.startsWith(path.resolve(squadsDir))) {
            return reply.status(403).send({ error: 'Forbidden' });
        }
        if (!fs.existsSync(resolved)) {
            return reply.status(404).send({ error: 'File not found' });
        }
        const content = fs.readFileSync(resolved, 'utf-8');
        return reply.send({ content });
    });
    // Save a file
    app.put('/api/files/:squad/*', { preHandler: [app.requireAuth] }, async (request, reply) => {
        const { squad } = request.params;
        const filePath = request.params['*'];
        if (!filePath)
            return reply.status(400).send({ error: 'Missing file path' });
        const resolved = path.resolve(squadsDir, squad, filePath);
        if (!resolved.startsWith(path.resolve(squadsDir))) {
            return reply.status(403).send({ error: 'Forbidden' });
        }
        const { content } = request.body;
        if (typeof content !== 'string') {
            return reply.status(400).send({ error: 'Content must be a string' });
        }
        // Ensure parent directory exists
        const dir = path.dirname(resolved);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        fs.writeFileSync(resolved, content, 'utf-8');
        return reply.send({ ok: true });
    });
}
//# sourceMappingURL=files-routes.js.map