import kv from "@workshop/shared/kv"
import type { EvalData } from "@workshop/shared/kv"
import type { Message, PartialMessage } from "discord.js"

export const storeEvaluation = async (message: Message | PartialMessage, emoji: string, ratedBy: string) => {
  try {
    const rating = emoji === "✅" ? "good" : emoji === "❌" ? "bad" : null
    if (!rating) {
      throw new Error(`Invalid evaluation emoji: ${emoji}`)
    }

    // If message is partial, fetch the full message
    let fullMessage: Message
    if (message.partial) {
      fullMessage = await message.fetch()
    } else {
      fullMessage = message
    }

    // Fetch conversation context using Discord API
    const context = await fetchConversationContext(fullMessage)

    let channelName = `${fullMessage.guild?.name} - ???`
    if ("name" in fullMessage.channel) {
      channelName = `${fullMessage.guild?.name} - ${fullMessage.channel.name}`
    }
    const evalData: EvalData = {
      channel: channelName,
      rating,
      context,
      ratedBy,
    }

    // Add to evaluations
    await kv.update("evaluations", [], (prev) => {
      return [...prev, evalData]
    })

    console.log(`📊 Evaluation stored: ${rating} rating for message ${fullMessage.id} by ${ratedBy}`)

    // React with thumbs up to acknowledge
    await fullMessage.react("👍")

    return evalData
  } catch (error) {
    console.error("Error storing evaluation:", error)
    throw error
  }
}

// Fetch conversation context around a message using Discord API
const fetchConversationContext = async (message: Message, contextSize = 5): Promise<EvalData["context"]> => {
  try {
    // Fetch messages before the target message (the conversation leading up to this response)
    const messagesBefore = await message.channel.messages.fetch({
      before: message.id,
      limit: contextSize,
    })

    // Include the target message and sort by timestamp
    const allMessages = [...messagesBefore.values(), message].sort(
      (a, b) => a.createdTimestamp - b.createdTimestamp
    )

    return allMessages.map((msg) => ({
      content: msg.content,
      role: msg.author.bot ? "assistant" : "user",
      author: msg.author.username,
    }))
  } catch (error) {
    console.error("Error fetching conversation context:", error)

    // Fallback to just the target message
    return [
      {
        content: message.content,
        role: message.author.bot ? "assistant" : "user",
        author: message.author.username,
      },
    ]
  }
}
