import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import test from 'node:test'

const root = resolve(import.meta.dirname, '..')
const config = JSON.parse(await readFile(resolve(root, 'config/offline-resources.json'), 'utf8'))

test('offline resource identifiers and destinations are unique and project-relative', () => {
  assert.equal(config.schemaVersion, 1)
  const resources = [...config.archives, ...config.mirrors]
  assert.equal(new Set(resources.map((entry) => entry.id)).size, resources.length)
  assert.equal(new Set(resources.map((entry) => entry.libraryPath)).size, resources.length)
  for (const resource of resources) {
    assert.ok(!resource.libraryPath.startsWith('/'), resource.id)
    assert.ok(!resource.libraryPath.split('/').includes('..'), resource.id)
    if (resource.restore) {
      assert.ok(!resource.restore.startsWith('/'), resource.id)
      assert.ok(!resource.restore.split('/').includes('..'), resource.id)
    }
  }
})

test('all pinned upstream sources declare full revisions', () => {
  const pinned = config.archives.filter((entry) => entry.revision)
  assert.ok(pinned.length >= 7)
  for (const resource of pinned) assert.match(resource.revision, /^[0-9a-f]{40}$/, resource.id)
})

test('offline profile covers runtime, native sources, browsers and host recovery', () => {
  const ids = new Set([...config.archives, ...config.mirrors].map((entry) => entry.id))
  for (const id of [
    'project-node-modules',
    'freecad-source',
    'bitbybit-source',
    'occt-source',
    'opencamlib-source',
    'camotics-worktree',
    'linuxcnc-worktree',
    'occt-history-dist',
    'freecad-naming-wasm-sdk',
    'planegcs-dist',
    'qt6-wasm-core-downloads',
    'qt6-wasm-core-source',
    'qt6-wasm-core-sdk',
    'playwright-browsers',
    'debian-package-cache',
  ]) assert.ok(ids.has(id), id)
})

test('offline profile restores the linked naming SDK and production Worker', () => {
  const byId = new Map(config.archives.map((resource) => [resource.id, resource]))
  assert.equal(byId.get('freecad-naming-wasm-sdk')?.source, '.cache/toolchains/freecad-naming-sdk')
  assert.equal(byId.get('freecad-naming-wasm-sdk')?.required, true)
  assert.equal(byId.get('occt-history-dist')?.source, 'native/occt-history/dist')
  assert.equal(byId.get('occt-history-dist')?.required, true)
})
