import { getFigmaConfig, getFigmaGeneratedSpecs, saveFigmaVisualQA, getFigmaFlows, saveFigmaFlows, } from '../../storage/figma-store.js';
import { getFigmaFile, parseFigmaUrl } from '../../engine/figma/api-client.js';
import { extractFlows } from '../../engine/figma/flow-analyzer.js';
import { exportFigmaFrameImage, createVisualQAResult, buildPlaceholderDiff, formatVisualQAReport, } from '../../engine/figma/visual-qa.js';
import { generateE2ETests, writeE2ETestFiles, formatE2EReport, } from '../../engine/figma/e2e-generator.js';
import { FIGMA_NOT_CONNECTED } from './shared.js';
export async function handleFigmaVisualDiffReport(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return FIGMA_NOT_CONNECTED;
    }
    const generatedSpecs = await getFigmaGeneratedSpecs(input.projectPath);
    const spec = generatedSpecs.find((s) => s.specId === input.specId);
    if (spec === undefined) {
        return {
            content: [{ type: 'text', text: `Spec ${input.specId} not found in Figma-generated specs.` }],
            isError: true,
        };
    }
    const parsed = parseFigmaUrl(input.figmaUrl);
    const results = [];
    for (const nodeId of spec.nodeIds) {
        const figmaImageUrl = await exportFigmaFrameImage(parsed.fileKey, nodeId, config.accessToken);
        const diffs = buildPlaceholderDiff('', figmaImageUrl);
        const result = createVisualQAResult(spec.specId, nodeId, figmaImageUrl, '', diffs);
        results.push(result);
    }
    await saveFigmaVisualQA(input.projectPath, results);
    const md = formatVisualQAReport(results);
    return { content: [{ type: 'text', text: md }] };
}
export async function handleGenerateFigmaE2ETests(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return FIGMA_NOT_CONNECTED;
    }
    let flows = await getFigmaFlows(input.projectPath);
    if (flows.length === 0) {
        const parsed = parseFigmaUrl(input.figmaUrl);
        const figmaFile = await getFigmaFile(parsed.fileKey, config.accessToken);
        flows = extractFlows(figmaFile);
        await saveFigmaFlows(input.projectPath, flows);
    }
    const filtered = input.sectionFilter !== undefined
        ? flows.filter((f) => f.section === input.sectionFilter)
        : flows;
    const outputDir = input.outputDir ?? 'e2e/figma';
    const result = generateE2ETests(filtered, outputDir);
    await writeE2ETestFiles(result, input.projectPath);
    const md = formatE2EReport(result);
    return { content: [{ type: 'text', text: md }] };
}
//# sourceMappingURL=visual-qa.js.map