"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = templateRoutes;
const index_js_1 = require("../modules/prompt-library/index.js");
async function templateRoutes(app, opts) {
    const tmplManager = opts.templateManager ?? (await import('../modules/image-engine/templates.js')).templateManager;
    const store = opts.dataStore ?? (await import('../modules/data-store/index.js')).dataStore;
    //  Prompt Library Endpoints 
    // GET /templates/categories  List unique prompt library categories
    app.get('/templates/categories', async (_request, reply) => {
        try {
            const categories = await (0, index_js_1.getCategories)();
            return reply.status(200).send({ success: true, data: categories });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // GET /templates  List all templates, optional ?category= and ?q= filters
    // Supports prompt-library filtering: category filters by category, q searches text
    // If both provided, filter by category first then search within results
    app.get('/templates', async (request, reply) => {
        const { category, q } = request.query;
        try {
            // If both category and q are provided, filter by category first then search within
            if (category && q) {
                const categoryResults = await (0, index_js_1.getPromptsByCategory)(category);
                const lowerQ = q.toLowerCase();
                const filtered = categoryResults.filter((t) => t.name.toLowerCase().includes(lowerQ) ||
                    t.category.toLowerCase().includes(lowerQ) ||
                    t.description.toLowerCase().includes(lowerQ));
                return reply.status(200).send({ success: true, data: filtered });
            }
            // If only category is provided, use prompt-library category filter
            if (category) {
                const results = await (0, index_js_1.getPromptsByCategory)(category);
                return reply.status(200).send({ success: true, data: results });
            }
            // If only q is provided, use prompt-library search
            if (q) {
                const results = await (0, index_js_1.searchPrompts)(q);
                return reply.status(200).send({ success: true, data: results });
            }
            // No filters  fall back to scene template listing (existing behavior)
            const templates = await tmplManager.listTemplates();
            return reply.status(200).send({ success: true, data: templates });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // GET /templates/:id  Get template by ID (checks prompt-library first, then scene templates)
    app.get('/templates/:id', async (request, reply) => {
        const { id } = request.params;
        try {
            // Try prompt-library first
            const promptTemplate = await (0, index_js_1.getPromptDetail)(id);
            if (promptTemplate) {
                return reply.status(200).send({ success: true, data: promptTemplate });
            }
            // Fall back to scene template store
            const template = await store.getTemplate(id);
            if (!template) {
                return reply.status(404).send({ success: false, error: 'Template not found' });
            }
            return reply.status(200).send({ success: true, data: template });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // POST /templates/:id/personalize  Personalize a prompt template with character DNA
    app.post('/templates/:id/personalize', async (request, reply) => {
        const { id } = request.params;
        const body = request.body;
        if (!body?.characterId) {
            return reply.status(400).send({
                success: false,
                error: 'Missing required field: characterId',
            });
        }
        try {
            const dna = await store.getCharacter(body.characterId);
            if (!dna) {
                return reply.status(404).send({ success: false, error: 'Character not found' });
            }
            const result = await (0, index_js_1.personalizeTemplate)(id, dna);
            if (!result) {
                return reply.status(404).send({ success: false, error: 'Template not found' });
            }
            return reply.status(200).send({ success: true, data: result });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    //  Scene Template CRUD Endpoints 
    // POST /templates  Create a new scene template
    app.post('/templates', async (request, reply) => {
        const body = request.body;
        if (!body || !body.name || !body.category || !body.promptTemplate || !body.environment || !body.defaultAspectRatio) {
            return reply.status(400).send({
                success: false,
                error: 'Missing required fields: name, category, promptTemplate, environment, defaultAspectRatio',
            });
        }
        try {
            const now = new Date().toISOString();
            const id = body.name.toLowerCase().replace(/\s+/g, '-') + '-' + Date.now();
            const template = {
                id,
                name: body.name,
                category: body.category,
                promptTemplate: body.promptTemplate,
                environment: body.environment,
                defaultAspectRatio: body.defaultAspectRatio,
                previewImageUrl: body.previewImageUrl,
                createdAt: now,
                updatedAt: now,
            };
            await store.saveTemplate(template);
            return reply.status(201).send({ success: true, data: template });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // PUT /templates/:id  Update scene template
    app.put('/templates/:id', async (request, reply) => {
        const { id } = request.params;
        const body = request.body;
        if (!body) {
            return reply.status(400).send({ success: false, error: 'Request body is required' });
        }
        try {
            const existing = await store.getTemplate(id);
            if (!existing) {
                return reply.status(404).send({ success: false, error: 'Template not found' });
            }
            const updated = {
                ...existing,
                name: body.name ?? existing.name,
                category: body.category ?? existing.category,
                promptTemplate: body.promptTemplate ?? existing.promptTemplate,
                environment: body.environment ?? existing.environment,
                defaultAspectRatio: body.defaultAspectRatio ?? existing.defaultAspectRatio,
                previewImageUrl: body.previewImageUrl ?? existing.previewImageUrl,
                updatedAt: new Date().toISOString(),
            };
            await store.saveTemplate(updated);
            return reply.status(200).send({ success: true, data: updated });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // DELETE /templates/:id  Delete scene template
    app.delete('/templates/:id', async (request, reply) => {
        const { id } = request.params;
        try {
            const existing = await store.getTemplate(id);
            if (!existing) {
                return reply.status(404).send({ success: false, error: 'Template not found' });
            }
            const deleted = await store.deleteTemplate(id);
            return reply.status(200).send({ success: true, data: { id, deleted } });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
}
//# sourceMappingURL=templates.js.map