import { getPolicyTemplate, listPolicyTemplatesWithKeys, applyPolicyTemplate, recommendTemplate, } from '@4runr/sentinel';
import { requireAuth } from '../middleware/auth.js';
import { readRateLimit, writeRateLimit } from '../middleware/rateLimit.js';
import { persistSentinelConfigAfterApply, hydrateSentinelConfigFromDisk, getSentinelLimitsFilePath, } from '../security/sentinel-config-store.js';
export async function sentinelPolicyRoutes(fastify) {
    fastify.get('/api/sentinel/policies/templates', {
        preHandler: [requireAuth, readRateLimit],
    }, async (request, reply) => {
        try {
            const templates = listPolicyTemplatesWithKeys();
            return {
                success: true,
                templates: templates.map(t => ({
                    key: t.key,
                    name: t.name,
                    description: t.description,
                    useCase: t.useCase,
                    config: t.config
                }))
            };
        }
        catch (error) {
            return reply.status(500).send({
                error: 'Failed to list templates',
                details: error.message
            });
        }
    });
    fastify.get('/api/sentinel/policies/templates/:name', {
        preHandler: [requireAuth, readRateLimit],
    }, async (request, reply) => {
        try {
            const { name } = request.params;
            const template = getPolicyTemplate(name);
            if (!template) {
                return reply.status(404).send({
                    error: 'Template not found',
                    available: listPolicyTemplatesWithKeys().map(t => t.key)
                });
            }
            return {
                success: true,
                template: {
                    name: template.name,
                    description: template.description,
                    useCase: template.useCase,
                    config: template.config
                }
            };
        }
        catch (error) {
            return reply.status(500).send({
                error: 'Failed to get template',
                details: error.message
            });
        }
    });
    fastify.post('/api/sentinel/policies/recommend', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const { useCase } = (request.body || {});
            if (!useCase) {
                return reply.status(400).send({
                    error: 'useCase is required'
                });
            }
            const recommendation = recommendTemplate(useCase);
            if (!recommendation) {
                return reply.status(404).send({
                    error: 'No recommendation found'
                });
            }
            return {
                success: true,
                recommended: {
                    name: recommendation.name,
                    description: recommendation.description,
                    useCase: recommendation.useCase,
                    config: recommendation.config,
                    reason: `Recommended for use case: ${useCase}`
                }
            };
        }
        catch (error) {
            return reply.status(500).send({
                error: 'Failed to get recommendation',
                details: error.message
            });
        }
    });
    fastify.post('/api/sentinel/policies/apply', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const { template: templateName } = (request.body || {});
            if (!templateName) {
                return reply.status(400).send({
                    error: 'template is required'
                });
            }
            const config = applyPolicyTemplate(templateName);
            if (!config) {
                return reply.status(404).send({
                    error: 'Template not found',
                    available: listPolicyTemplatesWithKeys().map(t => t.key)
                });
            }
            const { Sentinel } = await import('@4runr/sentinel');
            const sentinel = Sentinel.getInstance();
            try {
                sentinel.updateConfig(config);
                const savedTo = persistSentinelConfigAfterApply(sentinel, config, fastify.log);
                return {
                    success: true,
                    template: templateName,
                    config: config,
                    message: `Template '${templateName}' applied. Limits active and saved to ${savedTo}.`,
                };
            }
            catch (error) {
                return reply.status(400).send({
                    error: 'Failed to apply template',
                    details: error.message
                });
            }
        }
        catch (error) {
            return reply.status(500).send({
                error: 'Failed to apply template',
                details: error.message
            });
        }
    });
    fastify.post('/api/sentinel/policies/custom', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const body = (request.body || {});
            const { Sentinel } = await import('@4runr/sentinel');
            const sentinel = Sentinel.getInstance();
            const current = sentinel.getConfig();
            const num = (key, fallback) => {
                const v = body[key];
                if (typeof v === 'number' && Number.isFinite(v))
                    return v;
                if (typeof v === 'string' && v.trim() !== '') {
                    const n = Number(v);
                    if (Number.isFinite(n))
                        return n;
                }
                return fallback;
            };
            const config = {
                enabled: typeof body['enabled'] === 'boolean' ? body['enabled'] : current.enabled,
                runMaxDurationMs: num('runMaxDurationMs', current.runMaxDurationMs),
                runMaxTokens: num('runMaxTokens', current.runMaxTokens),
                runIdleMs: num('runIdleMs', current.runIdleMs),
                loopWindow: num('loopWindow', current.loopWindow),
                loopMax: num('loopMax', current.loopMax),
                runMaxCost: num('runMaxCost', current.runMaxCost ?? 1.0),
            };
            try {
                sentinel.updateConfig(config);
                const savedTo = persistSentinelConfigAfterApply(sentinel, config, fastify.log);
                return {
                    success: true,
                    config,
                    message: `Custom limits saved (${savedTo}). Reopen Sentinel or restart Gateway to reload; env vars override fields when set.`,
                };
            }
            catch (error) {
                const msg = error instanceof Error ? error.message : String(error);
                return reply.status(400).send({
                    error: 'Invalid custom config',
                    details: msg,
                });
            }
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            return reply.status(500).send({
                error: 'Failed to apply custom config',
                details: msg,
            });
        }
    });
    fastify.get('/api/sentinel/policies/current', {
        preHandler: [requireAuth, readRateLimit],
    }, async (request, reply) => {
        try {
            const { Sentinel } = await import('@4runr/sentinel');
            const sentinel = Sentinel.getInstance();
            hydrateSentinelConfigFromDisk(sentinel);
            return {
                success: true,
                config: sentinel.getConfig(),
                persistedPath: getSentinelLimitsFilePath(),
            };
        }
        catch (error) {
            return reply.status(500).send({
                error: 'Failed to get current config',
                details: error.message
            });
        }
    });
}
//# sourceMappingURL=sentinel-policies.js.map