import { pipe, toLower, trim, replace,split, join, map } from "ramda"

export const parsePluginFolderName = (
  folderName: string,
): { author: string; pluginName: string } => {
  const parts = folderName.split("__")

  if (parts.length !== 2) {
    return { author: "", pluginName: "" }
  }

  return { author: slugify(parts[0]), pluginName: slugify(parts[1]) }
}

// Helper function to capitalize first letter of a word
const capitalize = (word) => word.charAt(0).toUpperCase() + word.slice(1)

export const deslugify = pipe(
  replace(/^-|-$/g, ""), // Remove any leading/trailing dashes (defensive)
  split("-"), // Split on dashes to get words
  map(capitalize), // Capitalize each word
  join(" ") // Join with spaces
)

export const slugify = pipe(
  toLower,
  trim,
  replace(/\s+/g, "-"), // Replace spaces with dashes
  replace(/[^\w-]/g, ""), // Remove non-word chars except dashes
  replace(/-+/g, "-"), // Replace multiple dashes with single dash
  replace(/^-|-$/g, ""), // Remove leading/trailing dashes
)

export const getInstanceActionId = (
  pluginName: string,
  identifier: string,
  actionId: string,
  actionIdOverride = "",
) => {
  if (actionIdOverride.length) {
    return `plugin-${pluginName}-${actionIdOverride}`
  }
  return `plugin-${pluginName}-${identifier}-${actionId}`
}

export const generatePluginKey = (name:string, author:string):string=>`${slugify(author)}__${slugify(name)}`

export default {
  parsePluginFolderName,
  slugify,
  deslugify,
  getInstanceActionId,
  generatePluginKey,
}
