import { mkdirSync } from "node:fs"
import { getConfig } from "../config"
import { log } from "../log"

const crashLogDir = getConfig("dataDir")
mkdirSync(crashLogDir, { recursive: true })

const crashLogPath = `${crashLogDir}/crash.log`

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`

    // overwrite the crash log file
    const file = Bun.file(crashLogPath)
    file.write(crashLog)
  } catch (writeError) {
    log({ type: "error", error: writeError, context: "writing crash log" })
  }
}

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

const clearCrashLog = async () => {
  try {
    const file = Bun.file(crashLogPath)
    if (!(await file.exists())) return
    const contents = await file.text()
    await file.write("")

    if (contents.trim() !== "") {
      return contents
    }
  } catch (error) {
    log({ type: "error", error, context: "reading crash log" })
  }
}
