const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { getServerMode, getEmbedColor, EMBED_COLORS } = require('../utils/modeHelper');

function safeEval(expression) {
  const sanitized = expression.replace(/[^0-9+\-*/().%^sqrt\s]/gi, '');
  
  if (!sanitized || sanitized.trim() === '') {
    return { error: 'Invalid expression' };
  }

  try {
    let processed = sanitized
      .replace(/\^/g, '**')
      .replace(/sqrt\(([^)]+)\)/gi, 'Math.sqrt($1)');

    const result = Function('"use strict"; return (' + processed + ')')();
    
    if (typeof result !== 'number' || isNaN(result) || !isFinite(result)) {
      return { error: 'Result is not a valid number' };
    }
    
    return { result };
  } catch (e) {
    return { error: 'Invalid expression' };
  }
}

module.exports = {
  data: new SlashCommandBuilder()
    .setName('math')
    .setDescription('Calculate a math expression')
    .addStringOption(option =>
      option.setName('expression')
        .setDescription('The math expression (e.g., 2+2, sqrt(16), 5^2)')
        .setRequired(true)
        .setMaxLength(200)
    ),

  async execute(interaction, supabase, client) {
    const expression = interaction.options.getString('expression');
    const mode = await getServerMode(supabase, interaction.guildId);

    const { result, error } = safeEval(expression);

    if (error) {
      const embed = new EmbedBuilder()
        .setColor(EMBED_COLORS.error)
        .setTitle('🧮 Math Error')
        .setDescription(error)
        .setTimestamp();
      return interaction.reply({ embeds: [embed], ephemeral: true });
    }

    const formattedResult = Number.isInteger(result) ? result.toString() : result.toFixed(6).replace(/\.?0+$/, '');

    const embed = new EmbedBuilder()
      .setColor(getEmbedColor(mode))
      .setTitle('🧮 Calculator')
      .addFields(
        { name: '📥 Expression', value: `\`${expression}\`` },
        { name: '📤 Result', value: `\`${formattedResult}\`` }
      )
      .setTimestamp();

    await interaction.reply({ embeds: [embed] });
  },
};
