const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const OpenAI = require('openai');

const openai = new OpenAI({
  apiKey: process.env.AI_INTEGRATIONS_OPENAI_API_KEY,
  baseURL: process.env.AI_INTEGRATIONS_OPENAI_BASE_URL
});

const conversationHistory = new Map();
const MAX_HISTORY = 10;

module.exports = {
  data: new SlashCommandBuilder()
    .setName('ai')
    .setDescription('Chat with AeThex AI assistant')
    .addSubcommand(sub =>
      sub.setName('chat')
        .setDescription('Send a message to the AI')
        .addStringOption(opt =>
          opt.setName('message')
            .setDescription('Your message to the AI')
            .setRequired(true)))
    .addSubcommand(sub =>
      sub.setName('clear')
        .setDescription('Clear your conversation history'))
    .addSubcommand(sub =>
      sub.setName('image')
        .setDescription('Generate an image with AI')
        .addStringOption(opt =>
          opt.setName('prompt')
            .setDescription('Describe the image you want to generate')
            .setRequired(true))),

  async execute(interaction, supabase, client) {
    const subcommand = interaction.options.getSubcommand();

    if (subcommand === 'clear') {
      conversationHistory.delete(interaction.user.id);
      return interaction.reply({
        embeds: [new EmbedBuilder()
          .setColor(0x5865f2)
          .setDescription('Your conversation history has been cleared.')],
        ephemeral: true
      });
    }

    if (subcommand === 'image') {
      await interaction.deferReply();
      const prompt = interaction.options.getString('prompt');

      try {
        const response = await openai.images.generate({
          model: 'gpt-image-1',
          prompt: prompt,
          n: 1,
          size: '1024x1024'
        });

        const imageUrl = response.data[0]?.url || response.data[0]?.b64_json;

        if (!imageUrl) {
          return interaction.editReply({
            embeds: [new EmbedBuilder()
              .setColor(0xff0000)
              .setDescription('Failed to generate image. Please try again.')]
          });
        }

        const embed = new EmbedBuilder()
          .setColor(0x5865f2)
          .setTitle('AI Generated Image')
          .setDescription(`**Prompt:** ${prompt}`)
          .setImage(imageUrl)
          .setFooter({ text: `Requested by ${interaction.user.username}`, iconURL: interaction.user.displayAvatarURL() })
          .setTimestamp();

        return interaction.editReply({ embeds: [embed] });
      } catch (error) {
        console.error('AI image error:', error);
        return interaction.editReply({
          embeds: [new EmbedBuilder()
            .setColor(0xff0000)
            .setDescription('Failed to generate image. Please try again later.')]
        });
      }
    }

    if (subcommand === 'chat') {
      await interaction.deferReply();
      const userMessage = interaction.options.getString('message');

      try {
        let history = conversationHistory.get(interaction.user.id) || [];

        history.push({
          role: 'user',
          content: userMessage
        });

        const systemPrompt = `You are AeThex AI, a helpful and friendly assistant for the AeThex Discord community. You help users with questions about Discord, gaming, technology, and general topics. Keep responses concise but helpful. Be friendly and engaging. If asked about AeThex, explain it's a creative technology community focused on gaming, development, and digital arts.`;

        const messages = [
          { role: 'system', content: systemPrompt },
          ...history
        ];

        const completion = await openai.chat.completions.create({
          model: 'gpt-4o-mini',
          messages: messages,
          max_tokens: 1000,
          temperature: 0.7
        });

        const aiResponse = completion.choices[0]?.message?.content || 'I could not generate a response.';

        history.push({
          role: 'assistant',
          content: aiResponse
        });

        if (history.length > MAX_HISTORY * 2) {
          history = history.slice(-MAX_HISTORY * 2);
        }

        conversationHistory.set(interaction.user.id, history);

        let displayResponse = aiResponse;
        if (displayResponse.length > 4000) {
          displayResponse = displayResponse.substring(0, 4000) + '...';
        }

        const embed = new EmbedBuilder()
          .setColor(0x5865f2)
          .setAuthor({ 
            name: 'AeThex AI', 
            iconURL: client.user?.displayAvatarURL() || interaction.guild?.iconURL() 
          })
          .setDescription(displayResponse)
          .setFooter({ 
            text: `Requested by ${interaction.user.username}`, 
            iconURL: interaction.user.displayAvatarURL() 
          })
          .setTimestamp();

        return interaction.editReply({ embeds: [embed] });

      } catch (error) {
        console.error('AI chat error:', error);
        
        let errorMessage = 'Something went wrong while processing your request.';
        if (error.message?.includes('rate limit')) {
          errorMessage = 'Too many requests. Please wait a moment and try again.';
        } else if (error.message?.includes('quota')) {
          errorMessage = 'AI service quota exceeded. Please try again later.';
        }

        return interaction.editReply({
          embeds: [new EmbedBuilder()
            .setColor(0xff0000)
            .setDescription(errorMessage)]
        });
      }
    }
  }
};
