import fs from 'node:fs';
import path from 'node:path';
export const handleAuthoringRoutes = async (ctx, req, res, url) => {
    /* ── GET /api/specialists/custom ────────────────────────────────────── */
    if (req.method === 'GET' && url.pathname === '/api/specialists/custom') {
        const dir = path.join(ctx.repoRoot, '.agents', 'specialists');
        try {
            const files = await fs.promises.readdir(dir);
            const customs = await Promise.all(files
                .filter((f) => f.endsWith('.md'))
                .map(async (f) => {
                const specialistId = f.replace(/\.md$/, '');
                try {
                    const content = await fs.promises.readFile(path.join(dir, f), 'utf8');
                    const titleMatch = content.match(/^#\s+.+?([A-Za-z].*)/m);
                    const name = titleMatch ? titleMatch[1].trim() : specialistId;
                    return { specialistId, name, source: 'custom' };
                }
                catch {
                    return { specialistId, name: specialistId, source: 'custom' };
                }
            }));
            ctx.respondJson(res, customs);
        }
        catch {
            ctx.respondJson(res, []);
        }
        return true;
    }
    /* ── GET /api/skills/custom ─────────────────────────────────────────── */
    if (req.method === 'GET' && url.pathname === '/api/skills/custom') {
        const dir = path.join(ctx.repoRoot, '.agents', 'skills');
        try {
            const files = await fs.promises.readdir(dir);
            const customs = await Promise.all(files
                .filter((f) => f.endsWith('.md'))
                .map(async (f) => {
                const skillId = f.replace(/\.md$/, '');
                try {
                    const content = await fs.promises.readFile(path.join(dir, f), 'utf8');
                    const titleMatch = content.match(/^#\s+(.+)/m);
                    const name = titleMatch ? titleMatch[1].trim() : skillId;
                    return { skillId, name, source: 'custom' };
                }
                catch {
                    return { skillId, name: skillId, source: 'custom' };
                }
            }));
            ctx.respondJson(res, customs);
        }
        catch {
            ctx.respondJson(res, []);
        }
        return true;
    }
    return false;
};
