// engine/dashboard/routes.ts — HTTP route handlers for the dashboard server.
// Pattern matches req.url and dispatches to the appropriate handler.
import { loadAllProjects, loadProject, loadSpecDetail, computeHealthMetrics, loadUsageStats, } from './data-loader.js';
import { renderHomePage, renderProjectPage, renderSpecPage, render404Page, } from './templates-project.js';
/** Send an HTML response */
function sendHtml(res, status, html) {
    res.writeHead(status, {
        'Content-Type': 'text/html; charset=utf-8',
        'Cache-Control': 'no-cache',
    });
    res.end(html);
}
/** Send a JSON response */
function sendJson(res, status, data) {
    const body = JSON.stringify(data);
    res.writeHead(status, {
        'Content-Type': 'application/json; charset=utf-8',
        'Cache-Control': 'no-cache',
    });
    res.end(body);
}
/** Extract path segments ignoring empty strings and query */
function parsePath(url) {
    const withoutQuery = url.split('?')[0] ?? '';
    return withoutQuery.split('/').filter((s) => s.length > 0);
}
/** Handle GET / — home page with project list */
async function handleHome(res) {
    const [projects, usage] = await Promise.all([loadAllProjects(), loadUsageStats()]);
    sendHtml(res, 200, renderHomePage(projects, usage));
}
/** Handle GET /project/:id */
async function handleProjectPage(res, projectId) {
    const [project, usage] = await Promise.all([loadProject(projectId), loadUsageStats()]);
    if (!project) {
        sendHtml(res, 404, render404Page(`/project/${projectId}`));
        return;
    }
    const metrics = computeHealthMetrics(project);
    sendHtml(res, 200, renderProjectPage(project, metrics, usage));
}
/** Handle GET /spec/:projectId/:specId */
async function handleSpecPage(res, projectId, specId) {
    const [project, detail] = await Promise.all([
        loadProject(projectId),
        loadSpecDetail(projectId, specId),
    ]);
    const projectName = project?.name ?? projectId;
    sendHtml(res, 200, renderSpecPage(projectId, projectName, specId, detail.hu, detail.ficha, detail.progress));
}
/** Handle GET /api/projects */
async function handleApiProjects(res) {
    const projects = await loadAllProjects();
    sendJson(res, 200, projects);
}
/** Handle GET /api/project/:id */
async function handleApiProject(res, projectId) {
    const project = await loadProject(projectId);
    if (!project) {
        sendJson(res, 404, { error: 'Project not found' });
        return;
    }
    sendJson(res, 200, project);
}
/** Handle GET /api/usage */
async function handleApiUsage(res) {
    const usage = await loadUsageStats();
    sendJson(res, 200, usage);
}
/** Main route dispatcher — called by the HTTP server for every request */
export async function handleRequest(req, res) {
    // Only accept GET requests
    if (req.method !== 'GET') {
        sendJson(res, 405, { error: 'Method not allowed' });
        return;
    }
    const url = req.url ?? '/';
    const segments = parsePath(url);
    try {
        // GET /
        if (segments.length === 0) {
            await handleHome(res);
            return;
        }
        // GET /api/...
        if (segments[0] === 'api') {
            if (segments[1] === 'projects' && segments.length === 2) {
                await handleApiProjects(res);
                return;
            }
            if (segments[1] === 'project' && segments[2] !== undefined) {
                await handleApiProject(res, decodeURIComponent(segments[2]));
                return;
            }
            if (segments[1] === 'usage' && segments.length === 2) {
                await handleApiUsage(res);
                return;
            }
            sendJson(res, 404, { error: 'API endpoint not found' });
            return;
        }
        // GET /project/:id
        if (segments[0] === 'project' && segments[1] !== undefined) {
            await handleProjectPage(res, decodeURIComponent(segments[1]));
            return;
        }
        // GET /spec/:projectId/:specId
        if (segments[0] === 'spec' && segments[1] !== undefined && segments[2] !== undefined) {
            await handleSpecPage(res, decodeURIComponent(segments[1]), decodeURIComponent(segments[2]));
            return;
        }
        // 404
        sendHtml(res, 404, render404Page(url));
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        sendJson(res, 500, { error: message });
    }
}
//# sourceMappingURL=routes.js.map