/**
 * Worker Management Routes
 * HTTP API for managing workers with dashboard functionality
 */
import { Cloudflare, Env, Logger, Router } from '../../../../src/index.js';
import { HealthMonitor } from '../HealthMonitor.js';
import { ValidationSchemas, withCustomValidation } from '../http/middleware/CustomValidation.js';
import { withEditWorkerValidation } from '../http/middleware/EditWorkerValidation.js';
import { withDriverValidation } from '../http/middleware/ValidateDriver.js';
import { withCreateWorkerValidation, withWorkerOperationValidation, } from '../http/middleware/WorkerValidationChain.js';
import { WorkerApiController } from '../http/WorkerApiController.js';
import { WorkerController } from '../http/WorkerController.js';
import { ResourceMonitor } from '../ResourceMonitor.js';
import { TelemetryDashboard } from '../telemetry/index.js';
import { registerStaticAssets } from '../ui/router/ui.js';
import { WorkerFactory } from '../WorkerFactory.js';
const controller = WorkerController.create();
const apiController = WorkerApiController.create();
function registerCoreWorkerRoutes(r) {
    // Core worker operations
    Router.post(r, '/create', withCreateWorkerValidation(controller.create));
    Router.put(r, '/:name', withCreateWorkerValidation(controller.update));
    // Worker editing with custom validation that handles mapping
    Router.put(r, '/:name/edit', withEditWorkerValidation(controller.update));
    Router.post(r, '/:name/start', withDriverValidation(withWorkerOperationValidation(controller.start)));
    Router.post(r, '/:name/auto-start', withDriverValidation(withWorkerOperationValidation(controller.setAutoStart)));
    Router.post(r, '/:name/stop', withDriverValidation(withWorkerOperationValidation(controller.stop)));
    Router.post(r, '/:name/restart', withDriverValidation(withWorkerOperationValidation(controller.restart)));
    Router.post(r, '/:name/pause', withDriverValidation(withWorkerOperationValidation(controller.pause)));
    Router.post(r, '/:name/resume', withDriverValidation(withWorkerOperationValidation(controller.resume)));
    Router.del(r, '/:name', withDriverValidation(withWorkerOperationValidation(controller.remove)));
}
function registerWorkerQueryRoutes(r) {
    // Worker listing and filtering
    Router.get(r, '/', withDriverValidation(withCustomValidation(ValidationSchemas.workerFilter, apiController.listWorkers)));
    Router.get(r, '/:name', withDriverValidation(withWorkerOperationValidation(controller.get)));
    Router.get(r, '/:name/status', withWorkerOperationValidation(controller.status));
    Router.get(r, '/:name/creation-status', withWorkerOperationValidation(controller.getCreationStatus));
    Router.get(r, '/:name/metrics', withWorkerOperationValidation(controller.metrics));
    Router.get(r, '/:name/health', withWorkerOperationValidation(controller.health));
    // Worker details
    Router.get(r, '/:name/details', withDriverValidation(apiController.getWorkerDetailsHandler));
    // Worker driver data for editing
    Router.get(r, '/:name/driver-data', withDriverValidation(apiController.getWorkerDriverDataHandler));
}
function registerMonitoringRoutes(r) {
    // SSE events stream for monitoring + workers snapshot
    Router.get(r, '/events', controller.eventsStream);
    // Health monitoring
    Router.post(r, '/:name/monitoring/start', controller.startMonitoring);
    Router.post(r, '/:name/monitoring/stop', controller.stopMonitoring);
    Router.get(r, '/:name/monitoring/history', controller.healthHistory);
    Router.get(r, '/:name/monitoring/trend', controller.healthTrend);
    Router.put(r, '/:name/monitoring/config', controller.updateMonitoringConfig);
    // SLA monitoring
    Router.get(r, '/:name/sla/status', controller.getSlaStatus);
}
function registerVersioningRoutes(r) {
    // Versioning
    Router.post(r, '/:name/versions', controller.registerVersion);
    Router.get(r, '/:name/versions', controller.listVersions);
    Router.get(r, '/:name/versions/:version', controller.getVersion);
}
function registerUtilityRoutes(r) {
    // Utility endpoints
    Router.get(r, '/drivers', apiController.getDriversHandler);
    Router.get(r, '/queue-data', apiController.getQueueDataHandler);
    Router.get(r, '/health', apiController.getHealthSummaryHandler);
}
function registerWorkerLifecycleRoutes(router, middleware) {
    Router.group(router, '/api/workers', (r) => {
        Logger.info('Registering Worker Management Routes');
        registerCoreWorkerRoutes(r);
        if (Cloudflare.getWorkersEnv() === null) {
            registerMonitoringRoutes(r); // ← Move FIRST - has /events
            registerWorkerQueryRoutes(r);
            registerVersioningRoutes(r);
            registerUtilityRoutes(r);
        }
    }, { middleware: middleware });
}
function registerWorkerTelemetryRoutes(router, middleware) {
    const options = middleware ? { middleware } : undefined;
    Router.group(router, '/api', (r) => {
        Router.get(r, '/workers/system/summary', async (_req, res) => {
            const workers = WorkerFactory.list();
            const monitoringSummary = await HealthMonitor.getSummary();
            const resourceUsage = ResourceMonitor.getCurrentUsage('system');
            res.json({
                ok: true,
                summary: {
                    workers: workers.length,
                    monitoring: monitoringSummary,
                    resources: resourceUsage,
                },
            });
        });
        Router.get(r, '/workers/system/monitoring/summary', async (_req, res) => {
            const summary = await HealthMonitor.getSummary();
            res.json({ ok: true, summary });
        });
        Router.get(r, '/resources/current', async (_req, res) => {
            const usage = ResourceMonitor.getCurrentUsage('system');
            res.json({ ok: true, usage });
        });
        Router.get(r, '/resources/trends', async (req, res) => {
            const period = (req.getParam('period') ?? 'day');
            const trends = ResourceMonitor.getAllTrends('system', period);
            res.json({ ok: true, trends });
        });
    }, options);
}
export function registerWorkerRoutes(router, _options, routeOptions) {
    registerStaticAssets(router, routeOptions?.middleware ?? []);
    registerWorkerLifecycleRoutes(router, routeOptions?.middleware);
    registerWorkerTelemetryRoutes(router, routeOptions?.middleware);
    // Register Telemetry Dashboard
    const dashboard = TelemetryDashboard.create({
        basePath: '/telemetry',
    });
    dashboard.registerRoutes(router);
    const port = Env.get('PORT', '7777');
    Logger.info(`Worker routes registered at http://127.0.0.1:${port}/workers`);
    Logger.info(`Telemetry dashboard registered at http://127.0.0.1:${port}/telemetry`);
}
export default registerWorkerRoutes;
