import { getFigmaConfig, getFigmaEnrichment, getFigmaCodeConnect, getFigmaTokens, } from '../../storage/figma-store.js';
import { knowledgeStore } from '../../storage/index.js';
import { hashProjectPath } from '../../storage/base-store.js';
import { buildFigmaImplementationRules } from '../../engine/figma/implementation-rules.js';
import { getFigmaFile, parseFigmaUrl } from '../../engine/figma/api-client.js';
import { extractFrames, groupFramesBySection, groupFramesByBreakpoint, } from '../../engine/figma/frame-extractor.js';
import { FIGMA_NOT_CONNECTED } from './shared.js';
export async function handleListFigmaFrames(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return FIGMA_NOT_CONNECTED;
    }
    const parsed = parseFigmaUrl(input.figmaUrl);
    const figmaFile = await getFigmaFile(parsed.fileKey, config.accessToken);
    const frames = extractFrames(figmaFile);
    const sections = groupFramesBySection(frames, 'prefix');
    const lines = [
        '| Section | Frames | Example Node IDs |',
        '|---------|--------|-----------------|',
    ];
    for (const [sectionName, sectionFrames] of sections) {
        const exampleIds = sectionFrames
            .slice(0, 3)
            .map((f) => f.nodeId)
            .join(', ');
        lines.push(`| ${sectionName} | ${sectionFrames.length} | ${exampleIds} |`);
    }
    const totalFrames = frames.length;
    lines.push('', `Total: ${totalFrames} frames en ${sections.size} secciones. Use generate_specs_from_figma_file to create specs.`);
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
export async function handleListFigmaResponsiveFrames(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return FIGMA_NOT_CONNECTED;
    }
    const parsed = parseFigmaUrl(input.figmaUrl);
    const figmaFile = await getFigmaFile(parsed.fileKey, config.accessToken);
    const frames = extractFrames(figmaFile);
    const groups = groupFramesByBreakpoint(frames);
    const lines = ['## Responsive Frame Groups', ''];
    for (const [logicalName, group] of groups) {
        lines.push(`### ${logicalName}`);
        for (const f of group.frames.mobile) {
            lines.push(`- Mobile: ${f.name} (${f.nodeId})`);
        }
        for (const f of group.frames.tablet) {
            lines.push(`- Tablet: ${f.name} (${f.nodeId})`);
        }
        for (const f of group.frames.desktop) {
            lines.push(`- Desktop: ${f.name} (${f.nodeId})`);
        }
        for (const f of group.frames.unknown) {
            lines.push(`- Unknown: ${f.name} (${f.nodeId})`);
        }
        lines.push('');
    }
    if (groups.size === 0) {
        lines.push('No responsive frame groups detected.');
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
export async function handleGetFigmaContextForSpec(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Figma is not configured for this project. Run configure_figma first.',
                },
            ],
            isError: true,
        };
    }
    const enrichments = await getFigmaEnrichment(input.projectPath);
    const result = enrichments.find((e) => e.specId === input.specId);
    if (result === undefined) {
        return {
            content: [
                {
                    type: 'text',
                    text: `No design context for ${input.specId}. Run enrich_specs_from_figma first.`,
                },
            ],
        };
    }
    // SPEC-488: Load CodeConnect, tokens, and project stack for rules injection
    const projectId = hashProjectPath(input.projectPath);
    const [codeConnectEntries, tokens, knowledge] = await Promise.all([
        getFigmaCodeConnect(input.projectPath),
        getFigmaTokens(input.projectPath),
        knowledgeStore.getKnowledge(projectId),
    ]);
    const figmaImplementationRules = buildFigmaImplementationRules({
        codeConnectEntries,
        tokens,
        stack: knowledge?.stack ?? [],
        framework: knowledge?.framework ?? null,
    });
    const codeConnectComponents = codeConnectEntries.map((e) => ({
        nodeId: e.figmaNodeId,
        componentName: e.componentName,
        codebasePath: e.codeUrl,
    }));
    const lines = [`## Design Context for ${input.specId}`, ''];
    for (const ctx of result.contexts) {
        lines.push(`### ${ctx.frameName} (${ctx.nodeId})`);
        lines.push(ctx.description);
        if (ctx.componentHints.length > 0) {
            lines.push(`\n**Components**: ${ctx.componentHints.join(', ')}`);
        }
        if (ctx.layoutNotes.length > 0) {
            lines.push(`**Layout**: ${ctx.layoutNotes.join(', ')}`);
        }
        if (ctx.colorTokens.length > 0) {
            lines.push(`**Colors**: ${ctx.colorTokens.join(', ')}`);
        }
        lines.push('');
    }
    lines.push('## Implementation Rules (from Figma MCP official guide)', '');
    for (const rule of figmaImplementationRules) {
        lines.push(`- ${rule}`);
    }
    return {
        content: [{ type: 'text', text: lines.join('\n') }],
        structuredContent: {
            specId: input.specId,
            contexts: result.contexts,
            figmaImplementationRules,
            codeConnectComponents,
            figmaTokenCount: tokens.length,
        },
    };
}
//# sourceMappingURL=frames.js.map