import type { CommandPaletteOption } from '../../ui/components/CommandPalette'

export interface SkillPaletteItem {
  name: string
  description: string
  active: boolean
  label: string
}

export function formatSkillPaletteLabel(skillName: string): string {
  return `$${skillName}`
}

export function createSkillPaletteItems(
  skills: readonly Readonly<{ name: string, description: string }>[],
  activeSkillNames?: ReadonlySet<string>,
): SkillPaletteItem[] {
  return [...skills]
    .map((skill) => {
      const active = activeSkillNames?.has(skill.name) === true
      return {
        name: skill.name,
        description: skill.description,
        active,
        label: formatSkillPaletteLabel(skill.name),
      }
    })
    .sort((left, right) => {
      if (left.active !== right.active)
        return left.active ? -1 : 1
      return left.name.localeCompare(right.name)
    })
}

export function buildSkillPaletteOptions(
  items: readonly SkillPaletteItem[],
): CommandPaletteOption[] {
  return items.map(item => ({
    label: item.label,
    detail: item.description,
    keywords: [
      item.name,
      item.description,
      item.active ? 'active' : 'inactive',
    ],
  }))
}

export function resolveSkillNameFromPaletteLabel(
  items: readonly SkillPaletteItem[],
  label: string | null,
): string | null {
  if (!label)
    return null
  return items.find(item => item.label === label)?.name ?? null
}

export function toggleSkillActivation(
  activeSkillNames: Set<string>,
  skillName: string,
): boolean {
  if (activeSkillNames.has(skillName)) {
    activeSkillNames.delete(skillName)
    return false
  }
  activeSkillNames.add(skillName)
  return true
}
