// engine/figma/design-enricher.ts — Design enrichment for specs from Figma context (SPEC-420)
// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------
function rgbToHex(r, g, b) {
    const toHex = (v) => Math.round(v * 255)
        .toString(16)
        .padStart(2, '0');
    return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
function findNodeById(node, targetId) {
    if (node.id === targetId) {
        return node;
    }
    for (const child of node.children ?? []) {
        const found = findNodeById(child, targetId);
        if (found !== undefined) {
            return found;
        }
    }
    return undefined;
}
function collectSolidColors(node, colors, limit) {
    if (colors.size >= limit) {
        return;
    }
    for (const fill of node.fills ?? []) {
        if (fill.type === 'SOLID' && fill.color !== undefined) {
            const hex = rgbToHex(fill.color.r, fill.color.g, fill.color.b);
            colors.add(hex);
            if (colors.size >= limit) {
                return;
            }
        }
    }
    for (const child of node.children ?? []) {
        collectSolidColors(child, colors, limit);
        if (colors.size >= limit) {
            return;
        }
    }
}
// ---------------------------------------------------------------------------
// Public functions
// ---------------------------------------------------------------------------
export function buildDesignContext(nodeId, frameName, section, figmaDocument) {
    const node = findNodeById(figmaDocument, nodeId);
    if (node === undefined) {
        return {
            nodeId,
            frameName,
            section,
            description: `Frame '${frameName}' (node ${nodeId} not found in document)`,
            componentHints: [],
            layoutNotes: [],
            colorTokens: [],
            generatedAt: new Date().toISOString(),
        };
    }
    const childCount = node.children?.length ?? 0;
    const baseDescription = `Frame '${frameName}' in section '${section}'`;
    const description = childCount > 0 ? `${baseDescription} — contains ${childCount} child elements` : baseDescription;
    // Component hints: direct children of type COMPONENT or INSTANCE, max 10
    const componentHints = [];
    for (const child of node.children ?? []) {
        if (child.type === 'COMPONENT' || child.type === 'INSTANCE') {
            componentHints.push(child.name);
            if (componentHints.length >= 10) {
                break;
            }
        }
    }
    // Layout notes
    const layoutNotes = [];
    if (node.layoutMode !== undefined && node.layoutMode !== '') {
        const direction = node.layoutMode === 'HORIZONTAL'
            ? 'Horizontal layout'
            : node.layoutMode === 'VERTICAL'
                ? 'Vertical layout'
                : `${node.layoutMode} layout`;
        layoutNotes.push(direction);
    }
    if (childCount > 5) {
        layoutNotes.push(`Complex layout with ${childCount} elements`);
    }
    // Color tokens: scan recursively, max 5 unique colors
    const colorSet = new Set();
    collectSolidColors(node, colorSet, 5);
    return {
        nodeId,
        frameName,
        section,
        description,
        componentHints,
        layoutNotes,
        colorTokens: [...colorSet],
        generatedAt: new Date().toISOString(),
    };
}
export function enrichSpecsWithDesignContext(specs, file, frames) {
    return specs.map((spec) => {
        if (spec.nodeIds.length === 0) {
            return {
                specId: spec.specId,
                enriched: false,
                nodeIds: [],
                contexts: [],
                skippedReason: 'no nodeIds',
            };
        }
        const contexts = spec.nodeIds.map((nodeId) => {
            const frame = frames.find((f) => f.nodeId === nodeId);
            const frameName = frame?.name ?? nodeId;
            const section = frame?.section ?? spec.section;
            return buildDesignContext(nodeId, frameName, section, file.document);
        });
        return {
            specId: spec.specId,
            enriched: true,
            nodeIds: spec.nodeIds,
            contexts,
        };
    });
}
export function formatEnrichmentAsMarkdown(results) {
    const lines = ['## Figma Design Context', ''];
    for (const result of results) {
        if (!result.enriched) {
            lines.push(`### ${result.specId}`);
            lines.push(`_Skipped: ${result.skippedReason ?? 'unknown reason'}_`);
            lines.push('');
            lines.push('---');
            lines.push('');
            continue;
        }
        const frameCount = result.contexts.length;
        lines.push(`### ${result.specId}`);
        lines.push(`**Frames**: ${frameCount} enriched`);
        lines.push('');
        for (const ctx of result.contexts) {
            lines.push(`#### ${ctx.frameName} (node ${ctx.nodeId})`);
            lines.push(ctx.description);
            lines.push('');
            if (ctx.componentHints.length > 0) {
                lines.push(`**Component Hints**: ${ctx.componentHints.join(', ')}`);
            }
            if (ctx.layoutNotes.length > 0) {
                lines.push(`**Layout Notes**: ${ctx.layoutNotes.join(', ')}`);
            }
            if (ctx.colorTokens.length > 0) {
                lines.push(`**Colors**: ${ctx.colorTokens.join(', ')}`);
            }
            lines.push('');
        }
        lines.push('---');
        lines.push('');
    }
    return lines.join('\n');
}
export function getContextForSpec(specId, nodeIds, file, frames) {
    // specId is used by callers for identification — not needed in the lookup itself
    void specId;
    if (nodeIds.length === 0) {
        return [];
    }
    return nodeIds.map((nodeId) => {
        const frame = frames.find((f) => f.nodeId === nodeId);
        const frameName = frame?.name ?? nodeId;
        const section = frame?.section ?? '';
        return buildDesignContext(nodeId, frameName, section, file.document);
    });
}
//# sourceMappingURL=design-enricher.js.map