import { readdir } from 'node:fs/promises'
import path from 'node:path'
import { readJson, writeJson } from './lib.js'

const root = process.cwd()
const packagesJsonDir = path.join(root, 'packages', 'json')

const resourceDirs = (await readdir(packagesJsonDir, { withFileTypes: true }))
  .filter((entry) => entry.isDirectory())
  .map((entry) => entry.name)
  .sort((a, b) => a.localeCompare(b))

const resources = []
let generatedAt = null

for (const resourceId of resourceDirs) {
  const catalog = await readJson(path.join(packagesJsonDir, resourceId, 'catalog.json'))
  generatedAt = maxDate(generatedAt, catalog.generated_at)
  resources.push({
    id: catalog.id,
    resource_type: catalog.resource_type,
    title: catalog.title,
    short_title: catalog.short_title,
    abbreviation: catalog.abbreviation,
    alternate_ids: catalog.alternate_ids ?? [],
    language: catalog.language,
    script: catalog.script,
    canon: catalog.canon,
    translation: catalog.translation,
    contributors: catalog.contributors ?? [],
    features: catalog.features ?? [],
    attachments: catalog.attachments ?? {},
    source: catalog.source,
    license: catalog.license,
    catalog_display: catalog.catalog_display,
    package_path: `packages/json/${catalog.id}/catalog.json`,
    source_manifest_path: `sources/${catalog.source_manifest_file ?? `${catalog.id}.json`}`,
    detail_doc_path: `docs/resources/${catalog.id}.md`,
    counts: catalog.counts,
    files: catalog.files,
    checks: catalog.checks,
  })
}

await writeJson(path.join(packagesJsonDir, 'catalog.json'), {
  schema_version: 'librebible.index-catalog.v1',
  project: 'LibreBible',
  generated_at: generatedAt ?? new Date().toISOString(),
  resources,
})

console.log(`Generated packages/json/catalog.json with ${resources.length} resource(s).`)

function maxDate(current, candidate) {
  if (!candidate) return current
  if (!current) return candidate
  return new Date(candidate) > new Date(current) ? candidate : current
}
