export function useContentPrefix() {
  const config = useAppConfig()

  const locales: string[] = config.content.matrix.locale.list.map(l => l.code)
  const variants: string[] = config.content.matrix.variant.list.map(v => v.code)

  type Prefix = [string, string, string]
  let prefixes: Prefix[] = []

  if (locales.length>1 && variants.length>1) {
    prefixes = locales.flatMap(l => variants.map(v => [`/${l}/${v}`, l, v] as Prefix))
  } else if (locales.length>1 && variants.length===1) {
    prefixes = locales.map(l => [`/${l}`, l, variants[0]!])
  } else if (locales.length===1 && variants.length>1) {
    prefixes = variants.map(v => [`/${v}`, locales[0]!, v])
  } else if (locales.length===1 && variants.length===1) {
    prefixes = [['', locales[0]!, variants[0]!]]
  } else {
    console.warn('Missing locales and variants in AppConfig')
  }

  const terminators = new Set(['/', '#', '?'])

  function getLocaleVariant(path: string): [string, string] | undefined {
    for (const [p, l, v] of prefixes) {
      if (path.startsWith(p) && (path.length===p.length || terminators.has(path[p.length]))) {
        return [l, v]
      }
    }

    return undefined
  }

  function buildPrefix(locale: string, variant: string): string {
    let segments: string[] = []

    if (locales.length > 1) {
      segments.push(locale)
    }

    if (variants.length > 1) {
      segments.push(variant)
    }

    return (segments.length ? '/' : '') + segments.join('/')
  }

  return {getLocaleVariant, buildPrefix}
}
