// Resolves content slugs to file paths — topics in content/topics/ and TBR activities via glob.
import { globSync } from 'node:fs'
import { resolve } from 'node:path'

const ACTIVITY_PREFIX = /^c([1-4])-(.+)$/

const DIR_TO_TYPE = { topics: 'topic', bookends: 'bookend', breaks: 'break', schedules: 'schedule' }

// Resolves a content slug to its absolute file path and type, searching content/* dirs and TBR activity reference dirs.
export function resolveSlug(slug, { root }) {
  const activityMatch = slug.match(ACTIVITY_PREFIX)
  if (activityMatch) {
    const [, tier, name] = activityMatch
    const hits = globSync(resolve(root, `reference/tbr/c${tier}/**/${name}.md`))
    if (hits.length === 0) throw new Error(`activity not found: ${slug}`)
    if (hits.length > 1) throw new Error(`activity ambiguous: ${slug} matched ${hits.join(', ')}`)
    return { type: 'activity', path: hits[0] }
  }

  const hits = globSync(resolve(root, `content/*/${slug}/index.md`))
  if (hits.length === 0) throw new Error(`content not found: ${slug}`)
  if (hits.length > 1) throw new Error(`content ambiguous: ${slug} matched ${hits.join(', ')}`)

  const path = hits[0]
  const parts = path.split('/')
  const dir = parts[parts.length - 3]
  const type = DIR_TO_TYPE[dir] ?? dir.replace(/s$/, '')
  return { type, path }
}
