import { DEFAULT_PUBLIC_LOCALE, normalizePublicLocale } from '~/utils/public-locales'

const GUIDES_INDEX_MODULES = import.meta.glob('../generated/site/guides/index/*.js')
const GUIDES_BY_SLUG_MODULES = import.meta.glob('../generated/site/guides/by-slug/*.js')
const GUIDES_EXTRA_MODULES = import.meta.glob('../generated/site/guides/extra/*.js')

export const EMPTY_GUIDES_EXPORT = Object.freeze({
  guideItems: [],
  guidesBySlug: {},
  guidesIndex: [],
  scenicRoutes: [],
})

const guidesLocaleExportCache = new Map()

function guidesModuleLoader(modules, section, locale) {
  const normalizedLocale = normalizePublicLocale(locale)

  return modules[`../generated/site/guides/${section}/${normalizedLocale}.js`]
    || modules[`../generated/site/guides/${section}/${DEFAULT_PUBLIC_LOCALE}.js`]
    || null
}

async function loadGuidesModule(modules, section, locale) {
  const loader = guidesModuleLoader(modules, section, locale)

  if (!loader) {
    return null
  }

  return loader()
}

function mergeGuideItems(baseItems = [], extraItems = []) {
  const merged = new Map()

  for (const item of [...baseItems, ...extraItems]) {
    const key = String(item?.contentKey || item?.slug || item?.id || '').trim()

    if (!key) {
      continue
    }

    merged.set(key, item)
  }

  return [...merged.values()]
}

export async function loadGuidesLocaleExport(locale = DEFAULT_PUBLIC_LOCALE) {
  const normalizedLocale = normalizePublicLocale(locale)

  if (!guidesLocaleExportCache.has(normalizedLocale)) {
    guidesLocaleExportCache.set(normalizedLocale, (async () => {
      const [indexModule, bySlugModule] = await Promise.all([
        loadGuidesModule(GUIDES_INDEX_MODULES, 'index', normalizedLocale),
        loadGuidesModule(GUIDES_BY_SLUG_MODULES, 'by-slug', normalizedLocale),
      ])

      const extraModule = await loadGuidesModule(GUIDES_EXTRA_MODULES, 'extra', normalizedLocale)
      const extraGuidesBySlug = extraModule?.guidesBySlug || {}
      const extraGuideItems = extraModule?.guideItems || extraModule?.scenicRoutes || []
      const extraGuidesIndex = extraModule?.guidesIndex || extraGuideItems

      return {
        guideItems: mergeGuideItems(indexModule?.guideItems || [], extraGuideItems),
        guidesBySlug: {
          ...(bySlugModule?.guidesBySlug || {}),
          ...extraGuidesBySlug,
        },
        guidesIndex: mergeGuideItems(indexModule?.guidesIndex || [], extraGuidesIndex),
        scenicRoutes: mergeGuideItems(indexModule?.scenicRoutes || [], extraGuideItems),
      }
    })())
  }

  return guidesLocaleExportCache.get(normalizedLocale)
}
