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

export const slugify = (text: string) => {
  return text
    .toString()
    .normalize("NFD") // Remove accents
    .replace(/[\u0300-\u036F]/g, "") // Remove diacritics
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s._-]/g, "") // Hyphen at the end, no escape needed
    .replace(/\s+/g, "-") // Replace spaces with hyphens
    .replace(/-+/g, "-") // Remove duplicate hyphens
    .replace(/^-+|-+$/g, "") // Trim hyphens from start/end
}

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

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
  }
}
