import { expect, test } from 'bun:test'
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { extractSounds, UI_SOUNDS } from '../tools/extract-assets'

test('sound refresh copies only used bytes and preserves prior assets when any source is absent', () => {
  const root = mkdtempSync(path.join(tmpdir(), 'fmm-sounds-'))
  try {
    const core = path.join(root, 'core'), out = path.join(root, 'out')
    mkdirSync(path.join(core, 'sound'), { recursive: true })
    expect(extractSounds(core, out, 'fixture')).toBe(false)
    for (const [name] of UI_SOUNDS) writeFileSync(path.join(core, 'sound', `${name}.ogg`), `fixture-${name}`)
    expect(extractSounds(core, out, 'fixture')).toBe(true)
    for (const [name] of UI_SOUNDS) expect(readFileSync(path.join(out, 'sounds', `${name}.ogg`))).toEqual(readFileSync(path.join(core, 'sound', `${name}.ogg`)))
    const before = readFileSync(path.join(out, 'sounds/index.json'))
    rmSync(path.join(core, 'sound', 'gui-click.ogg'))
    expect(extractSounds(core, out, 'other')).toBe(false)
    expect(readFileSync(path.join(out, 'sounds/index.json'))).toEqual(before)
    expect(readFileSync(path.join(out, 'sounds/gui-click.ogg'), 'utf8')).toBe('fixture-gui-click')
  } finally { rmSync(root, { recursive: true, force: true }) }
})

test('packaged audio inventory matches the used subset and its original byte hashes', () => {
  const dir = path.resolve(import.meta.dir, '../assets/game/sounds')
  const inventory = JSON.parse(readFileSync(path.join(dir, 'index.json'), 'utf8')) as { gameVersion: string, clips: { name: string, gain: number, sha256: string }[] }
  expect(inventory.gameVersion).toBe('2.0.77')
  expect(inventory.clips.map(clip => [clip.name, clip.gain])).toEqual(UI_SOUNDS.map(([name, gain]) => [name, gain]))
  for (const clip of inventory.clips) {
    expect(new Bun.CryptoHasher('sha256').update(readFileSync(path.join(dir, `${clip.name}.ogg`))).digest('hex')).toBe(clip.sha256)
  }
})
