import { mapNodeToCSS } from './property-mapper.js';
/**
 * Parse a Pencil frame name into template metadata.
 * Expects format: "Template XX - Name"
 */
export function parseFrameName(name) {
    const match = name.match(/^Template\s+(\d+)\s*-\s*(.+)$/i);
    if (!match)
        return null;
    const num = parseInt(match[1], 10);
    const templateName = match[2].trim();
    const slug = templateName.toLowerCase().replace(/\s+/g, '-');
    return { number: num, name: templateName, slug };
}
/**
 * Generate a template .md from a Pencil frame and its children.
 */
export function generateTemplateMarkdown(frame) {
    const meta = parseFrameName(frame.name);
    const title = meta
        ? `Template ${String(meta.number).padStart(2, '0')} — ${meta.name}`
        : frame.name;
    const lines = [
        `# ${title}`,
        '',
        `**Dimensions:** ${frame.width}x${frame.height}`,
        '',
        '---',
        '',
    ];
    if (frame.children.length === 0) {
        lines.push('> No child nodes found in this frame.');
        return lines.join('\n');
    }
    for (const child of frame.children) {
        lines.push(`## ${child.name}`);
        lines.push('');
        const css = mapNodeToCSS(child);
        if (css) {
            lines.push('```css');
            lines.push(css);
            lines.push('```');
            lines.push('');
        }
    }
    return lines.join('\n');
}
/**
 * Compare Pencil frames with existing .md files and determine sync actions.
 */
export function computeSyncActions(frames, existingMds) {
    const actions = [];
    const matchedMds = new Set();
    for (const frame of frames) {
        const meta = parseFrameName(frame.name);
        if (!meta)
            continue; // Skip non-template frames
        const filename = `template-${String(meta.number).padStart(2, '0')}-${meta.slug}.md`;
        const content = generateTemplateMarkdown(frame);
        if (existingMds.includes(filename)) {
            matchedMds.add(filename);
            actions.push({ type: 'update', filename, frame, content });
        }
        else {
            actions.push({ type: 'create', filename, frame, content });
        }
    }
    // Find orphaned .md files (no matching frame)
    for (const md of existingMds) {
        if (!matchedMds.has(md)) {
            actions.push({ type: 'orphan', filename: md });
        }
    }
    return actions;
}
