const fs = require('fs');
const { EmbedBuilder } = require('discord.js');

module.exports = function parseEmbed(filepath, embedName, vars = {}) {
  const content = fs.readFileSync(filepath, 'utf-8');
  const blockRegex = new RegExp(`@embed\\s+${embedName}\\s*\\n([\\s\\S]*?)(?=@embed\\s|$)`);
  const block = content.match(blockRegex);
  if (!block) throw new Error(`Embed "${embedName}" not found in ${filepath}`);

  const inject = s => s.replace(/\$\{(\w+)\}/g, (_, k) => vars[k] ?? '');
  const lines = block[1].split('\n').map(l => l.trim()).filter(Boolean);
  const embed = new EmbedBuilder();
  const fields = [];
  let attachment = null;
  let pendingField = {};

  const flushField = () => {
    if (pendingField.name && pendingField.value) {
      fields.push({ name: pendingField.name, value: pendingField.value, inline: pendingField.inline ?? false });
    }
    pendingField = {};
  };

  for (const line of lines) {
    const [key, ...rest] = line.split('=');
    const k = key.trim();
    const v = inject(rest.join('=').trim().replace(/^["']|["']$/g, ''));

    if (k === 'title') embed.setTitle(v);
    else if (k === 'color') embed.setColor(parseInt(v));
    else if (k === 'description') embed.setDescription(v);
    else if (k === 'footer') embed.setFooter({ text: v });
    else if (k === 'timestamp' && v === 'true') embed.setTimestamp();
    else if (k === 'attachment') attachment = v;
    else if (k === 'field.name') { flushField(); pendingField.name = v; }
    else if (k === 'field.value') pendingField.value = v;
    else if (k === 'field.inline') pendingField.inline = v === 'true';
  }
  flushField();
  if (fields.length) embed.addFields(fields);

  return { embed, attachment };
};