import { getFigmaConfig, saveFigmaCodeConnect } from '../../storage/figma-store.js';
import { getFigmaFile, parseFigmaUrl } from '../../engine/figma/api-client.js';
import { extractFrames } from '../../engine/figma/frame-extractor.js';
import { fetchCodeConnectMappings, formatCodeConnectAsMarkdown, calculateCoverage, } from '../../engine/figma/code-connect-fetcher.js';
import { FIGMA_NOT_CONNECTED } from './shared.js';
export async function handleSyncFigmaCodeConnect(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return FIGMA_NOT_CONNECTED;
    }
    const parsed = parseFigmaUrl(input.figmaUrl);
    let entries;
    try {
        entries = await fetchCodeConnectMappings(parsed.fileKey, config.accessToken);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
            content: [{ type: 'text', text: `Error fetching Code Connect: ${msg}` }],
            isError: true,
        };
    }
    await saveFigmaCodeConnect(input.projectPath, entries);
    const figmaFile = await getFigmaFile(parsed.fileKey, config.accessToken);
    const frames = extractFrames(figmaFile);
    const allNodeIds = frames.map((f) => f.nodeId);
    const coveragePct = calculateCoverage(allNodeIds, entries);
    const md = formatCodeConnectAsMarkdown(entries);
    return {
        content: [
            {
                type: 'text',
                text: `${md}\n\n**Coverage**: ${coveragePct.toString()}% (${entries.length} components mapped / ${allNodeIds.length} total frames)`,
            },
        ],
    };
}
//# sourceMappingURL=code-connect.js.map