export const logCrash = async (error: unknown) => {
  try {
    const stack = error instanceof Error ? error.stack : ""
    const message = error instanceof Error ? error.message : String(error)

    const crashLog = `Spike crashed at ${new Date().toISOString()}:\n${message}\n${stack ?? ""}\n`
    console.error(crashLog)

    // overwrite the crash log file
    const file = Bun.file(`${process.env.DATA_DIR}/crash.log`)
    file.write(crashLog)
  } catch (error) {
    console.error("Failed to write crash log:", error)
  }
}

export const alertAboutCrashLog = async (client: any) => {
  try {
    const channelId = process.env.CHANNEL_ID ?? "1382121375619223594"
    const crashLog = await clearCrashLog()
    if (crashLog) {
      console.warn("⚠️ Previous crash log found:")
      const channel = await client.channels.fetch(channelId)
      if (channel?.isSendable()) {
        channel.send(`⚠️ Previous crash log found:\n\`\`\`${crashLog}\`\`\``)
      }
    }
  } catch (error) {
    console.error("Failed to alert about crash log:", error)
  }
}

const clearCrashLog = async () => {
  try {
    const file = Bun.file(`${process.env.DATA_DIR}/crash.log`)
    if (!(await file.exists())) return
    const contents = await file.text()
    await file.write("")

    if (contents.trim() !== "") {
      return contents
    }
  } catch (error) {
    console.error("Failed to read crash log:", error)
  }
}
