import { getFigmaConfig, appendFigmaSyncEntry, getFigmaGeneratedSpecs, saveFigmaGeneratedSpecs, saveFigmaEnrichment, saveFigmaFlows, saveFigmaSnapshot, getFigmaVersions, saveFigmaVersions, getFigmaCodeConnect, } from '../../storage/figma-store.js';
import { getFigmaFile, parseFigmaUrl } from '../../engine/figma/api-client.js';
import { extractFrames, groupFramesBySection } from '../../engine/figma/frame-extractor.js';
import { generateSpecsForSections } from '../../engine/figma/spec-generator.js';
import { extractFlows } from '../../engine/figma/flow-analyzer.js';
import { framesToSnapshot } from '../../engine/figma/change-detector.js';
import { fetchLatestFigmaVersion } from '../../engine/figma/version-tracker.js';
import { enrichSpecsWithDesignContext, formatEnrichmentAsMarkdown, } from '../../engine/figma/design-enricher.js';
import { FIGMA_NOT_CONNECTED } from './shared.js';
export async function handleGenerateSpecsFromFigma(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 groupBy = input.groupBy ?? 'prefix';
    const sections = groupFramesBySection(frames, groupBy);
    const generatedSpecs = await generateSpecsForSections(input.projectPath, sections, input.sectionFilter);
    const existingSpecs = await getFigmaGeneratedSpecs(input.projectPath);
    await saveFigmaGeneratedSpecs(input.projectPath, [...existingSpecs, ...generatedSpecs]);
    const now = new Date().toISOString();
    const syncEntry = {
        id: `sync-${Date.now()}`,
        fileKey: parsed.fileKey,
        syncedAt: now,
        status: 'success',
        specsCreated: generatedSpecs.length,
        framesProcessed: frames.length,
    };
    await appendFigmaSyncEntry(input.projectPath, syncEntry);
    const lines = [
        `Created ${generatedSpecs.length} specs from ${frames.length} frames:`,
        '',
    ];
    for (const spec of generatedSpecs) {
        lines.push(`- **${spec.section}**: ${spec.specId} (${spec.frameCount} frames)`);
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
export async function handleEnrichSpecsFromFigma(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 generatedSpecs = await getFigmaGeneratedSpecs(input.projectPath);
    const specIdsToFilter = input.specIds;
    const specsToEnrich = specIdsToFilter !== undefined && specIdsToFilter.length > 0
        ? generatedSpecs.filter((s) => specIdsToFilter.includes(s.specId))
        : generatedSpecs;
    const results = enrichSpecsWithDesignContext(specsToEnrich.map((s) => ({ specId: s.specId, nodeIds: s.nodeIds, section: s.section })), figmaFile, frames);
    await saveFigmaEnrichment(input.projectPath, results);
    // SPEC-488: inject Code Connect criteria into enrichment markdown
    const codeConnectEntries = await getFigmaCodeConnect(input.projectPath);
    const md = formatEnrichmentAsMarkdown(results);
    let codeConnectHint = '';
    if (codeConnectEntries.length > 0) {
        const criteriaLines = codeConnectEntries.map((e) => `- GIVEN ${e.componentName} WHEN rendered THEN uses \`${e.codeUrl}\`, not a generated div`);
        codeConnectHint = [
            '',
            '## Code Connect — Required Implementation Criteria',
            '> Add these to your spec criteria to enforce component reuse:',
            '',
            ...criteriaLines,
        ].join('\n');
    }
    return { content: [{ type: 'text', text: md + codeConnectHint }] };
}
export async function handleImportFigmaProject(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return FIGMA_NOT_CONNECTED;
    }
    const parsed = parseFigmaUrl(input.figmaUrl);
    const steps = [];
    // Step 1: Fetch file
    const figmaFile = await getFigmaFile(parsed.fileKey, config.accessToken);
    const frames = extractFrames(figmaFile);
    steps.push(`- Fetched file: ${frames.length} frames`);
    // Step 2: Extract flows
    const flows = extractFlows(figmaFile);
    await saveFigmaFlows(input.projectPath, flows);
    steps.push(`- Extracted ${flows.length} prototype flows`);
    // Step 3: Take snapshot
    const snapshot = framesToSnapshot(frames);
    await saveFigmaSnapshot(input.projectPath, snapshot);
    steps.push(`- Snapshot saved (${snapshot.length} frames)`);
    // Step 4: Generate specs
    const sections = groupFramesBySection(frames, 'prefix');
    const generatedSpecs = await generateSpecsForSections(input.projectPath, sections);
    const existingSpecs = await getFigmaGeneratedSpecs(input.projectPath);
    await saveFigmaGeneratedSpecs(input.projectPath, [...existingSpecs, ...generatedSpecs]);
    steps.push(`- Generated ${generatedSpecs.length} specs`);
    // Step 5: Enrich specs with design context
    const enrichResults = enrichSpecsWithDesignContext(generatedSpecs.map((s) => ({ specId: s.specId, nodeIds: s.nodeIds, section: s.section })), figmaFile, frames);
    await saveFigmaEnrichment(input.projectPath, enrichResults);
    steps.push(`- Enriched ${enrichResults.filter((r) => r.enriched).length} specs with design context`);
    // Step 6: Track version
    const currentVersion = await fetchLatestFigmaVersion(parsed.fileKey, config.accessToken);
    const versions = await getFigmaVersions(input.projectPath);
    versions[parsed.fileKey] = currentVersion;
    await saveFigmaVersions(input.projectPath, versions);
    steps.push(`- Version tracked: ${currentVersion}`);
    // Step 7: Log sync
    const now = new Date().toISOString();
    const syncEntry = {
        id: `import-${Date.now()}`,
        fileKey: parsed.fileKey,
        syncedAt: now,
        status: 'success',
        specsCreated: generatedSpecs.length,
        framesProcessed: frames.length,
    };
    await appendFigmaSyncEntry(input.projectPath, syncEntry);
    const summary = [
        '## Figma Project Import Complete',
        '',
        ...steps,
        '',
        `**File**: ${figmaFile.name}`,
        `**Specs created**: ${generatedSpecs.length}`,
        `**Flows mapped**: ${flows.length}`,
        '',
        'Next steps:',
        '- Run `generate_figma_e2e_tests` to create Playwright tests from flows',
        '- Run `extract_figma_design_tokens` to extract design tokens',
        '- Run `figma_visual_diff_report` to compare implementation vs design',
    ].join('\n');
    return { content: [{ type: 'text', text: summary }] };
}
//# sourceMappingURL=specs.js.map