// engine/figma/token-extractor.ts — Figma Design Tokens extractor (SPEC-421)
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function resolveTokenCategory(name) {
    const lower = name.toLowerCase();
    if (lower.includes('color') || lower.includes('colour')) {
        return 'color';
    }
    if (lower.includes('font') || lower.includes('text') || lower.includes('typography')) {
        return 'typography';
    }
    if (lower.includes('spacing') ||
        lower.includes('padding') ||
        lower.includes('margin') ||
        lower.includes('gap')) {
        return 'spacing';
    }
    if (lower.includes('radius') || lower.includes('corner') || lower.includes('rounded')) {
        return 'radius';
    }
    if (lower.includes('shadow') || lower.includes('elevation')) {
        return 'shadow';
    }
    return 'other';
}
function normalizeTokenName(name) {
    return name.replace(/\//g, '.').toLowerCase();
}
function formatColorValue(v) {
    const r = Math.round((v.r ?? 0) * 255);
    const g = Math.round((v.g ?? 0) * 255);
    const b = Math.round((v.b ?? 0) * 255);
    const a = v.a ?? 1;
    if (a === 1) {
        const hex = [r, g, b].map((c) => c.toString(16).padStart(2, '0').toUpperCase()).join('');
        return `#${hex}`;
    }
    return `rgba(${r},${g},${b},${a})`;
}
function formatTokenValue(type, value) {
    if (type === 'COLOR') {
        return formatColorValue(value);
    }
    if (type === 'FLOAT') {
        return `${value}px`;
    }
    if (type === 'STRING') {
        return value;
    }
    if (type === 'BOOLEAN') {
        return value ? 'true' : 'false';
    }
    return JSON.stringify(value);
}
// ---------------------------------------------------------------------------
// findDefaultModeId — returns the defaultModeId for the collection that owns
// the variable, falling back to the first modeId found in valuesByMode.
// ---------------------------------------------------------------------------
function findDefaultModeId(collections, valuesByMode) {
    for (const col of Object.values(collections)) {
        if (col.defaultModeId in valuesByMode) {
            return col.defaultModeId;
        }
    }
    const firstKey = Object.keys(valuesByMode)[0];
    return firstKey ?? '';
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
export async function fetchFigmaTokens(fileKey, accessToken) {
    const url = `https://api.figma.com/v1/files/${fileKey}/variables/local`;
    const response = await fetch(url, {
        headers: { 'X-Figma-Token': accessToken },
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Figma Variables API error ${response.status}: ${body}`);
    }
    const data = (await response.json());
    const { variables, variableCollections } = data.meta;
    const tokens = [];
    for (const variable of Object.values(variables)) {
        const modeId = findDefaultModeId(variableCollections, variable.valuesByMode);
        const rawValue = variable.valuesByMode[modeId];
        if (rawValue === undefined) {
            continue;
        }
        const category = resolveTokenCategory(variable.name);
        const name = normalizeTokenName(variable.name);
        const value = formatTokenValue(variable.resolvedType, rawValue);
        tokens.push({ category, name, value, rawValue });
    }
    tokens.sort((a, b) => {
        if (a.category < b.category) {
            return -1;
        }
        if (a.category > b.category) {
            return 1;
        }
        if (a.name < b.name) {
            return -1;
        }
        if (a.name > b.name) {
            return 1;
        }
        return 0;
    });
    return tokens;
}
export function groupTokensByCategory(tokens) {
    const map = new Map();
    for (const token of tokens) {
        const existing = map.get(token.category) ?? [];
        existing.push(token);
        map.set(token.category, existing);
    }
    return map;
}
export function formatTokensAsMarkdown(groups) {
    if (groups.size === 0) {
        return 'No design tokens found. Check your Figma plan (Variables require Figma Professional or higher).';
    }
    const sections = [];
    for (const [category, tokens] of groups) {
        if (tokens.length === 0) {
            continue;
        }
        const rows = tokens.map((t) => `| ${t.name} | ${t.value} |`).join('\n');
        sections.push(`## ${category}\n\n| Name | Value |\n|------|-------|\n${rows}`);
    }
    if (sections.length === 0) {
        return 'No design tokens found. Check your Figma plan (Variables require Figma Professional or higher).';
    }
    return sections.join('\n\n');
}
//# sourceMappingURL=token-extractor.js.map