import { nexusEventBus } from '../../engines/event-bus.js';
export const handleArchitectsRoutes = async (ctx, req, res, url) => {
    /* ── GET /api/architects/escalations ─────────────────────────────────── */
    if (req.method === 'GET' && url.pathname === '/api/architects/escalations') {
        const architects = ctx.getArchitects();
        if (!architects) {
            ctx.respondJson(res, { escalations: [], notReady: true, reason: 'Architects runtime not initialised.' });
            return true;
        }
        const raw = architects.getWardEscalations?.() ?? [];
        const escalations = raw.map((e) => ({
            wardId: e.strikeTeamId ?? null,
            consecutiveCriticalPatrols: e.consecutiveCriticalPatrols ?? 0,
            message: e.message ?? '',
            severity: (e.consecutiveCriticalPatrols ?? 0) >= 3 ? 'critical' : 'high',
            escalatedAt: e.report?.detectedAt ?? Date.now(),
            report: e.report ?? null,
        }));
        ctx.respondJson(res, { escalations });
        return true;
    }
    /* ── GET /api/architects/wards ───────────────────────────────────────── */
    if (req.method === 'GET' && url.pathname === '/api/architects/wards') {
        const architects = ctx.getArchitects();
        if (!architects) {
            ctx.respondJson(res, { notReady: true, reason: 'Architects runtime not initialised.', dispatch: null, worklist: [] });
            return true;
        }
        const dispatch = architects.getDispatchStatus?.() ?? null;
        const preferred = ctx.getPreferredArchitectsWorklist(url, url.searchParams.get('worklistId'), url.searchParams.get('strikeTeamId'));
        ctx.respondJson(res, {
            dispatch,
            worklist: Array.isArray(preferred?.items) ? preferred.items : [],
            worklistId: preferred?.worklistId ?? preferred?.worklist?.id ?? null,
            activeLocks: [],
            idle: Boolean(preferred?.idle),
            reason: preferred?.reason ?? '',
        });
        return true;
    }
    /* ── POST /api/architects/wards/:wardId/resolve ──────────────────────── */
    if (req.method === 'POST' && /^\/api\/architects\/wards\/[^/]+\/resolve$/.test(url.pathname)) {
        const wardId = url.pathname.split('/')[4];
        const architects = ctx.getArchitects();
        if (!architects) {
            ctx.respondJson(res, { ok: false, error: 'architects-unavailable' }, 503);
            return true;
        }
        nexusEventBus.emit('dashboard.action', { action: 'architects.ward.resolve', status: 'ok', target: wardId });
        ctx.respondJson(res, { ok: true, wardId });
        return true;
    }
    return false;
};
