"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDesignRouter = void 0;
const express_1 = require("express");
const logger_1 = require("../utils/logger");
const index_core_1 = require("../index-core");
const CommentVariationService_1 = require("../services/CommentVariationService");
const VariantCodeGeneratorService_1 = require("../services/VariantCodeGeneratorService");
const WorktreeManager_1 = require("../services/WorktreeManager");
const log = (0, logger_1.createLogger)('DesignRoutes');
const MAX_FILE_MATCHES_PER_ELEMENT = 6;
const MIN_VARIANT_COUNT = 2;
const MAX_VARIANT_COUNT = 5;
const enrichElementFilePaths = async (projectPath, element) => {
    if (element.filePaths && element.filePaths.length > 0) {
        return element;
    }
    const searchService = new index_core_1.ComponentSearchService();
    try {
        const matches = await searchService.findMatchingComponents(projectPath, element);
        if (matches.length === 0)
            return element;
        return {
            ...element,
            filePaths: matches
                .slice(0, MAX_FILE_MATCHES_PER_ELEMENT)
                .map((m) => ({ filePath: m.filePath })),
        };
    }
    catch (e) {
        log.warn('File path enrichment failed for variation request', e);
        return element;
    }
};
const createDesignRouter = (projectPath) => {
    const router = (0, express_1.Router)();
    router.post('/design/comment-variations', async (req, res) => {
        try {
            const body = req.body ?? {};
            const instruction = String(body.instruction ?? '').trim();
            const element = body.element;
            const variantCount = Number(body.variantCount);
            const model = typeof body.model === 'string' && body.model.trim().length > 0
                ? body.model.trim()
                : undefined;
            if (!instruction) {
                return res.status(400).json({
                    error: 'instruction is required',
                });
            }
            if (!element || typeof element.xpath !== 'string') {
                return res.status(400).json({
                    error: 'element with xpath is required',
                });
            }
            if (!Number.isInteger(variantCount) ||
                variantCount < MIN_VARIANT_COUNT ||
                variantCount > MAX_VARIANT_COUNT) {
                return res.status(400).json({
                    error: 'variantCount must be an integer between 2 and 5',
                });
            }
            const enriched = await enrichElementFilePaths(projectPath, element);
            const variants = await (0, CommentVariationService_1.generateCommentStyleVariants)({
                instruction,
                element: enriched,
                variantCount,
                projectPath,
                model,
            });
            res.json({ variants });
        }
        catch (e) {
            const message = e instanceof Error ? e.message : 'Variation failed';
            log.error('comment-variations error:', message);
            res.status(500).json({ error: message });
        }
    });
    router.post('/design/generate-variant-code', async (req, res) => {
        const body = req.body ?? {};
        const sessionId = String(body.sessionId ?? '').trim();
        const instruction = String(body.instruction ?? '').trim();
        const element = body.element;
        const variants = body.variants;
        const currentAppliedDiff = typeof body.currentAppliedDiff === 'string' &&
            body.currentAppliedDiff.trim().length > 0
            ? body.currentAppliedDiff
            : undefined;
        if (!sessionId) {
            return res.status(400).json({ error: 'sessionId is required' });
        }
        if (!instruction) {
            return res.status(400).json({ error: 'instruction is required' });
        }
        if (!element || typeof element.xpath !== 'string') {
            return res.status(400).json({ error: 'element with xpath is required' });
        }
        if (!Array.isArray(variants) || variants.length === 0) {
            return res.status(400).json({ error: 'variants array is required' });
        }
        res.setHeader('Content-Type', 'text/event-stream');
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Connection', 'keep-alive');
        res.flushHeaders();
        const sendEvent = (event) => {
            if (!res.writableEnded) {
                res.write(`data: ${JSON.stringify(event)}\n\n`);
            }
        };
        const abortController = new AbortController();
        req.on('close', () => abortController.abort());
        try {
            await (0, VariantCodeGeneratorService_1.generateVariantCode)({
                sessionId,
                projectPath,
                instruction,
                element,
                variants,
                currentAppliedDiff,
                onEvent: sendEvent,
                abortController,
            });
        }
        catch (e) {
            log.error('generate-variant-code error:', e);
        }
        finally {
            if (!res.writableEnded)
                res.end();
        }
    });
    router.post('/design/apply-variant-diff', async (req, res) => {
        const { diff, reverse } = req.body ?? {};
        if (!diff || typeof diff !== 'string') {
            return res.status(400).json({ error: 'diff is required' });
        }
        const manager = new WorktreeManager_1.WorktreeManager(projectPath);
        try {
            await manager.applyDiff(diff, Boolean(reverse));
            res.json({ ok: true });
        }
        catch (e) {
            const error = e instanceof Error ? e.message : 'Apply failed';
            log.error('apply-variant-diff error:', error);
            res.status(500).json({ ok: false, error });
        }
    });
    return router;
};
exports.createDesignRouter = createDesignRouter;
//# sourceMappingURL=design.js.map