import { eventBus } from "./eventBus"
import { generateImage, getFilenameFromUrl, uploadImageToBucket } from "./lib"

export const slugify = (text: string) => {
  return text
    .toLowerCase()
    .replace(/ /g, "-")
    .replace(/[^\w.-]+/g, "")
}

export const randomUUID = () => {
  return Math.random().toString(36).substring(2, 15)
}

export const processImage = async (
  tutorialDir: string,
  url: string,
  description: string,
  rigoToken: string
) => {
  try {
    const filename = getFilenameFromUrl(url)

    const imagePath = tutorialDir + "/.learn" + "/assets/" + filename

    eventBus.emit("course-generation", {
      message: `🖼️ Generating image ${imagePath}`,
    })

    const res = await generateImage(rigoToken, { prompt: description })
    await uploadImageToBucket(res.image_url, imagePath)

    eventBus.emit("course-generation", {
      message: `✅ Image ${imagePath} generated successfully!`,
    })
    return true
  } catch {
    return false
  }
}
