// engine/figma/api-client.ts — Figma REST API client (SPEC-418)
const FIGMA_API_BASE = 'https://api.figma.com/v1';
// ---------------------------------------------------------------------------
// parseFigmaUrl — extracts fileKey (and optional nodeId) from a Figma URL
// ---------------------------------------------------------------------------
export function parseFigmaUrl(url) {
    // Supported patterns:
    //   https://www.figma.com/design/:fileKey/:name
    //   https://www.figma.com/design/:fileKey/:name?node-id=:nodeId
    //   https://www.figma.com/file/:fileKey/:name
    let parsed;
    try {
        parsed = new URL(url);
    }
    catch {
        throw new Error(`Invalid Figma URL: ${url}`);
    }
    const segments = parsed.pathname.split('/').filter(Boolean);
    // segments: ['design' | 'file', fileKey, ...rest]
    const keyIndex = segments.findIndex((s) => s === 'design' || s === 'file');
    const fileKey = keyIndex >= 0 ? segments[keyIndex + 1] : undefined;
    if (fileKey === undefined || fileKey === '') {
        throw new Error(`Could not extract file key from Figma URL: ${url}`);
    }
    const rawNodeId = parsed.searchParams.get('node-id') ?? undefined;
    const nodeId = rawNodeId !== undefined ? rawNodeId.replace(/-/g, ':') : undefined;
    return { fileKey, nodeId };
}
// ---------------------------------------------------------------------------
// getFigmaMe — verify token and get current user info
// ---------------------------------------------------------------------------
export async function getFigmaMe(accessToken) {
    const response = await fetch(`${FIGMA_API_BASE}/me`, {
        headers: { 'X-Figma-Token': accessToken },
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Figma API error ${response.status}: ${body}`);
    }
    const data = (await response.json());
    return {
        id: data.id ?? '',
        name: data.handle ?? data.name ?? 'Unknown',
        email: data.email,
    };
}
// ---------------------------------------------------------------------------
// getFigmaFile — fetch a Figma file document tree
// ---------------------------------------------------------------------------
export async function getFigmaFile(fileKey, accessToken) {
    const response = await fetch(`${FIGMA_API_BASE}/files/${fileKey}`, {
        headers: { 'X-Figma-Token': accessToken },
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Figma API error ${response.status} for file ${fileKey}: ${body}`);
    }
    return (await response.json());
}
//# sourceMappingURL=api-client.js.map