import { respondToUserMessage } from "../ai"
import { storeEvaluation } from "../eval"
import { ActivityType, type Client } from "discord.js"
import { runCommand } from "./commands"

export const listenForEvents = (client: Client) => {
  client.on("interactionCreate", async (interaction) => {
    return runCommand(interaction)
  })

  client.on("messageCreate", async (msg) => {
    if (msg.author.bot) return

    try {
      // if it is a dm always respond, if it is a guild message, only respond if the bot is at mentioned
      if (!msg.guild || msg.mentions.has(client.user!)) {
        const response = await respondToUserMessage(msg)
        if (response) {
          if (response.length > 2000) {
            const chunks = response.match(/.{1,2000}/g) || [] // Discord has a 2000 character limit, so we need to split the response
            for (const chunk of chunks) {
              await msg.channel.send(chunk)
            }
          } else {
            await msg.channel.send(response)
          }
        }
      }
    } catch (error) {
      console.error("Error handling messageCreate event:", error)
      msg.channel.send("An error occurred 💥.")
    }
  })

  client.on("messageReactionAdd", async (reaction, user) => {
    if (user.bot) return

    const emoji = reaction.emoji.name

    // Only process evaluation emojis
    if (emoji === "✅" || emoji === "❌") {
      await storeEvaluation(reaction.message, emoji, user.username || user.id)
    }
  })

  client.on("ready", () => {
    // set the bots description
    const branch = process.env.RENDER_GIT_BRANCH || "unknown"
    const commit = process.env.RENDER_GIT_COMMIT?.slice(0, 7) || "deadbeef"
    client.user?.client.user?.setActivity(`${branch}@${commit}`, {
      type: ActivityType.Playing,
      state: `Error Count: ${0}`,
      url: `https://github.com/${process.env.RENDER_GIT_REPO_SLUG}/commit/${commit}`,
    })
  })

  client.on("error", (error) => {
    console.error("Discord client error:", error)
  })

  client.on("warn", (info) => {
    console.warn("Discord client warning:", info)
  })
}
