/** Offline M4 packaging checks and captures; all mutable app data is in an OS temp dir. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { decodePng } from './bench/png'

const root = path.resolve(import.meta.dir, '..')
const out = path.join(root, 'out/m4')
const temp = mkdtempSync(path.join(tmpdir(), 'fmm-m4-'))
const cache = path.join(temp, 'cache')
const settings = path.join(temp, 'settings')
mkdirSync(out, { recursive: true })
mkdirSync(settings)
const exe = path.join(root, 'target/release/fmm.exe')
const fixture = path.join(root, 'crates/app/tests/fixtures/r2b.json')
const env = { ...process.env, FACTORIO_DIR: '', FMM_CACHE_DIR: cache, FMM_SETTINGS_DIR: settings }
writeFileSync(path.join(out, 'capture-temp.txt'), temp)
let log = ''
function capture(name: string, args: string[] = [], binary = exe, useFixture = true, extraEnv = {}) {
  const output = path.join(out, name + '.png')
  const result = spawnSync(binary, ['--screenshot', output, '--size', '1440x945', '--catalogue', path.join(temp, 'absent.json'), ...(useFixture ? ['--fixture', fixture] : []), ...args], {
    cwd: temp, env: { ...env, ...extraEnv }, windowsHide: true, encoding: 'utf8',
  })
  log += `${name}: ${result.status}\n${result.stdout}${result.stderr}\n`
  writeFileSync(path.join(out, 'captures.log'), log)
  if (result.error) throw result.error
  assert.equal(result.status, 0, log)
  console.log(name)
  return readFileSync(output)
}
const main = capture('manage')
capture('settings', ['--settings-open', '1'])
capture('settings-1000', ['--settings-open', '1', '--size', '1000x600'])
capture('settings-env', ['--settings-open', '1'], exe, true, { FACTORIO_DIR: path.join(temp, 'environment-install') })
writeFileSync(path.join(settings, 'settings.json'), JSON.stringify({ installDir: path.join(temp, 'custom-install'), catalogueRefreshHours: 24 }))
capture('settings-saved', ['--settings-open', '1'])
writeFileSync(path.join(settings, 'settings.json'), 'broken json')
capture('settings-corrupt')
assert.equal(readFileSync(path.join(settings, 'settings.json'), 'utf8'), 'broken json')
writeFileSync(path.join(settings, 'settings.json'), JSON.stringify({ installDir: path.join(temp, 'missing-install'), catalogueRefreshHours: 6 }))
capture('settings-recovery', [], exe, false)
writeFileSync(path.join(settings, 'settings.json'), '{}')

// A real release PE must use the GUI subsystem and contain every original ICO image resource.
const pe = readFileSync(exe)
const header = pe.readUInt32LE(0x3c)
assert.equal(pe.toString('ascii', header, header + 4), 'PE\0\0')
const optional = header + 24
assert.equal(pe.readUInt16LE(optional), 0x20b, 'Expected PE32+')
assert.equal(pe.readUInt16LE(optional + 68), 2, 'Expected Windows GUI subsystem')
const sectionCount = pe.readUInt16LE(header + 6)
const sectionStart = optional + pe.readUInt16LE(header + 20)
function offset(rva: number) {
  for (let i = 0; i < sectionCount; i++) {
    const s = sectionStart + i * 40
    const start = pe.readUInt32LE(s + 12)
    if (rva >= start && rva < start + Math.max(pe.readUInt32LE(s + 8), pe.readUInt32LE(s + 16))) return pe.readUInt32LE(s + 20) + rva - start
  }
  throw new Error(`Unmapped resource RVA ${rva}`)
}
const resources = offset(pe.readUInt32LE(optional + 112 + 16))
function entries(relative: number): [number, number][] {
  const start = resources + relative
  const count = pe.readUInt16LE(start + 12) + pe.readUInt16LE(start + 14)
  return Array.from({ length: count }, (_, i) => [pe.readUInt32LE(start + 16 + i * 8), pe.readUInt32LE(start + 20 + i * 8)])
}
function blobs(relative: number): Buffer[] {
  return entries(relative).flatMap(([, value]) => {
    if (value & 0x80000000) return blobs(value & 0x7fffffff)
    const data = resources + value
    const start = offset(pe.readUInt32LE(data))
    return [pe.subarray(start, start + pe.readUInt32LE(data + 4))]
  })
}
const types = entries(0)
const iconType = types.find(([id]) => id === 3)
assert.ok(iconType, 'Missing RT_ICON')
assert.ok(types.some(([id]) => id === 14), 'Missing RT_GROUP_ICON')
const embedded = blobs(iconType[1] & 0x7fffffff)
const ico = readFileSync(path.join(root, 'assets/game/factorio.ico'))
const iconCount = ico.readUInt16LE(4)
for (let i = 0; i < iconCount; i++) {
  const entry = 6 + i * 16
  const start = ico.readUInt32LE(entry + 12)
  const image = ico.subarray(start, start + ico.readUInt32LE(entry + 8))
  assert.ok(embedded.some(b => b.equals(image)), `ICO image ${i} missing from exe`)
}

const packageDir = path.join(temp, 'package')
mkdirSync(packageDir)
const copiedExe = path.join(packageDir, 'fmm.exe')
copyFileSync(exe, copiedExe)
const assets = path.resolve(root, 'assets/game')
const hidden = path.resolve(root, 'assets/game-m4-hidden')
assert.ok(assets.startsWith(root + path.sep) && hidden.startsWith(root + path.sep))
assert.ok(!existsSync(hidden), 'Refuse to overwrite hidden asset directory')
renameSync(assets, hidden)
try {
  const copied = capture('manage-standalone', [], copiedExe)
  assert.deepEqual(decodePng(copied).data, decodePng(main).data, 'Copied exe must render identically without checkout assets')
  capture('settings-standalone', ['--settings-open', '1'], copiedExe)
} finally {
  renameSync(hidden, assets)
}
const report = `Windows GUI subsystem: 2\nEmbedded icon images: ${iconCount}/${iconCount} byte-identical to game ICO\nExe bytes: ${pe.length}\nStandalone Manage RGBA: identical\nTemporary app data/package: ${temp}\n`
writeFileSync(path.join(out, 'packaging.txt'), report)
console.log(report)
