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

const root = process.cwd()
const sourceDir = path.join(root, 'sources')
const files = (await readdir(sourceDir)).filter((file) => file.endsWith('.json'))

for (const file of files) {
  const manifestPath = path.join(sourceDir, file)
  const manifest = await readJson(manifestPath)
  const cachePath = path.join(root, 'cache', manifest.id, path.basename(manifest.source.download_url))

  await downloadFile(manifest.source.download_url, cachePath)
  const actual = await sha256File(cachePath)
  const expected = manifest.checks.expected_sha256?.toLowerCase()
  const status = expected === actual ? 'unchanged' : 'changed'

  console.log(`${manifest.id}: ${status}`)
  console.log(`  expected: ${expected}`)
  console.log(`  actual:   ${actual}`)

  if (status === 'changed') {
    process.exitCode = 1
  }
}
