"use strict";
// ABOUTME: Component search API routes
// ABOUTME: Handles searching for React components that match selected DOM elements
Object.defineProperty(exports, "__esModule", { value: true });
exports.createComponentRouter = void 0;
const express_1 = require("express");
const index_core_1 = require("../index-core");
const log = (0, index_core_1.createLogger)('ComponentRoutes');
// These will be sent to the LLM as context
const MAX_FILE_MATCHES_PER_ELEMENT = 6;
const createComponentRouter = (projectPath, telemetry) => {
    const router = (0, express_1.Router)();
    // Component search endpoint
    router.post('/search-components', async (req, res) => {
        const startTime = Date.now();
        try {
            const body = req.body;
            // Handle both single element and array of elements
            const elements = Array.isArray(body) ? body : [body];
            log.info(`Searching for components matching ${elements.length} element(s)`);
            log.debug('Elements summary:', elements.map((el, i) => ({
                index: i,
                tagName: el.tagName,
                className: el.className,
                id: el.id,
                textContent: el.textContent?.substring(0, 30),
            })));
            const searchService = new index_core_1.ComponentSearchService();
            // Process all elements in parallel
            const results = await Promise.all(elements.map(async (element, index) => {
                try {
                    const matches = await searchService.findMatchingComponents(projectPath, element);
                    log.debug(`Element ${index} (${element.tagName}): Found ${matches.length} matches`);
                    return { matches, error: null };
                }
                catch (error) {
                    log.warn(`Component search failed for element ${index}:`, error);
                    return {
                        matches: [],
                        error: error instanceof Error ? error.message : 'Unknown error',
                    };
                }
            }));
            const totalMatches = results.reduce((sum, result) => sum + result.matches.length, 0);
            const searchTimeMs = Date.now() - startTime;
            log.info(`Search completed: ${totalMatches} total matches across ${elements.length} element(s)`);
            // Track successful component search
            telemetry?.trackComponentSearch({
                success: true,
                resultCount: totalMatches,
                searchTimeMs,
            });
            // Return elements with filePaths populated from search results
            const elementsWithFilePaths = elements
                .map((element, index) => {
                const result = results[index];
                if (result && !result.error && result.matches.length > 0) {
                    const topMatches = result.matches.slice(0, MAX_FILE_MATCHES_PER_ELEMENT);
                    return {
                        ...element,
                        filePaths: topMatches.map((m) => ({
                            filePath: m.filePath,
                        })),
                    };
                }
                log.debug(`No component file found for element ${index}: <${element.tagName}>` +
                    `${element.className ? ` class="${element.className}"` : ''}` +
                    `${element.id ? ` id="${element.id}"` : ''}`);
                return null;
            })
                .filter((el) => el !== null);
            // Return elements with filePath already set
            const response = { elements: elementsWithFilePaths };
            res.json(response);
        }
        catch (error) {
            log.error('Component search failed:', error);
            const errorResponse = {
                error: 'Component search failed',
                details: error instanceof Error ? error.message : 'Unknown error',
            };
            res.status(500).json(errorResponse);
        }
    });
    return router;
};
exports.createComponentRouter = createComponentRouter;
//# sourceMappingURL=components.js.map