/** Offline M6 capture matrix. All app data and mod snapshots live in an OS temp directory. */
import { spawnSync } from 'node:child_process'
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, 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/m6')
const temp = mkdtempSync(path.join(tmpdir(), 'fmm-m6-'))
const cache = path.join(temp, 'cache')
const metadata = path.join(temp, 'metadata')
for (const folder of [out, cache, metadata, path.join(cache, 'portal-thumbs')]) mkdirSync(folder, { recursive: true })
writeFileSync(path.join(out, 'capture-data.txt'), temp)
const save = (name: string, data: unknown) => {
  const file = path.join(temp, name + '.json')
  writeFileSync(file, JSON.stringify(data))
  return file
}
const key = (s: string) => {
  let h = 0xcbf29ce484222325n
  for (const b of Buffer.from(s)) h = BigInt.asUintN(64, (h ^ BigInt(b)) * 0x100000001b3n)
  return h.toString(16).padStart(16, '0')
}
const catalogue = JSON.parse(readFileSync(path.join(root, 'crates/app/tests/fixtures/catalogue-small.json'), 'utf8')) as { results: any[] }
const mods = catalogue.results.slice(0, 14).map((m, i) => {
  const version = '1.0.0'
  const thumbnail = `/assets/m6-${i}.png`
  const full = { ...m, summary: i === 0 ? 'Calculate production rates and balance every machine in your factory. Works with Space Age and modded recipes.' : m.summary,
    thumbnail, description: `${m.title}\n\nOffline metadata fixture with a durable description, tags and gallery.`, images: [], tags: ['utility'],
    releases: [{ version: '2.0.0', sha1: '1'.repeat(40), info_json: { factorio_version: '2.0', dependencies: ['base'] } }],
    latest_release: { version: '2.0.0', info_json: { factorio_version: '2.0' } } }
  catalogue.results[i] = full
  writeFileSync(path.join(metadata, `${m.name}_${version}.json`), JSON.stringify(full))
  const image = path.join(root, 'assets/game/icons1x', i % 2 ? 'space-age.png' : 'missing-thumbnail.png')
  const url = 'https://assets-mod.factorio.com' + thumbnail
  copyFileSync(image, path.join(cache, 'portal-thumbs', key(url) + '.png'))
  copyFileSync(image, path.join(metadata, key(url) + '.png'))
  return { name: m.name, title: m.title, version, author: m.owner, description: 'Local fallback description.', factorioVersion: '2.0', dependencies: [], source: 'zip', path: path.join(temp, `${m.name}_${version}.zip`), thumbnail: null }
})
const builtin = ['base', 'elevated-rails', 'quality', 'space-age'].map(name => ({ ...mods[0], name, title: name, version: '2.0.77', source: 'builtin', author: 'Wube', description: 'Built-in game content.' }))
const fixture = save('fixture', { snapshot: {
  paths: { installDir: path.join(temp, 'install'), userDir: path.join(temp, 'user'), modsDir: path.join(temp, 'user/mods'), modListPath: path.join(temp, 'user/mods/mod-list.json'), gameVersion: '2.0.77' },
  builtin, mods, scanErrors: [], modList: { mods: [...builtin, ...mods].map(m => ({ name: m.name, enabled: true })) },
}, select: mods[0]!.name })
catalogue.results = catalogue.results.slice(0, 15)
const cat = save('catalogue', catalogue)
const absent = path.join(temp, 'absent.json')
let log = ''
function capture(exe: string, name: string, file: string, args: string[], size = '1440x945') {
  const result = spawnSync(path.join(root, exe), ['--screenshot', path.join(out, name + '.png'), '--fixture', file, '--size', size, '--catalogue', absent, ...args], {
    cwd: root, env: { ...process.env, FMM_CACHE_DIR: cache, FMM_METADATA_DIR: metadata, FMM_SETTINGS_DIR: path.join(temp, 'settings') }, encoding: 'utf8', windowsHide: true,
  })
  log += `${name}: ${result.status}\n${result.stdout}${result.stderr}\n`
  writeFileSync(path.join(out, 'captures.log'), log)
  if (result.error) throw result.error
  if (result.status !== 0) throw new Error(log)
  console.log(name)
}
const exe = 'target/release/fmm.exe'
const baseline = path.join(root, 'crates/app/tests/fixtures/r2b.json')
capture('out/m6/fmm-master.exe', 'manage-master', baseline, [])
capture(exe, 'manage-table', baseline, [])
const before = decodePng(readFileSync(path.join(out, 'manage-master.png')))
const after = decodePng(readFileSync(path.join(out, 'manage-table.png')))
if (Buffer.compare(Buffer.from(before.data), Buffer.from(after.data))) throw new Error('Default Manage RGBA differs from master')
console.log('Default Manage RGBA equals master')
for (const tab of ['manage', 'updates']) for (const view of ['rows', 'grid']) {
  capture(exe, `${tab}-${view}`, fixture, ['--tab', tab, '--view', view, '--catalogue', cat, '--portal-updates', cat, ...(tab === 'updates' ? ['--updates-select', mods[0]!.name] : [])])
}
for (const size of ['1280x945', '1920x945']) capture(exe, `explore-grid-${size}`, fixture, ['--tab', 'explore', '--view', 'grid', '--catalogue', cat], size)
capture(exe, 'grid-hover-selected', fixture, ['--tab', 'explore', '--view', 'grid', '--catalogue', cat, '--explore-select', mods[13]!.name, '--pointer', '365,245'], '1920x945')
capture(exe, 'table-toolbar-hover', baseline, ['--pointer', '100,122'])
capture(exe, 'grid-settings', fixture, ['--view', 'grid', '--catalogue', cat, '--settings-open', '1'])
capture(exe, 'manage-grid-1000', fixture, ['--view', 'grid', '--catalogue', cat], '1000x600')
capture(exe, 'updates-grid-1000', fixture, ['--tab', 'updates', '--view', 'grid', '--catalogue', cat, '--portal-updates', cat], '1000x600')
capture(exe, 'updates-grid-search-1000', fixture, ['--tab', 'updates', '--view', 'grid', '--catalogue', cat, '--portal-updates', cat, '--updates-search', 'Factory'], '1000x600')
// Wheel reaches the second virtualized page of installed cards without touching the filesystem.
capture(exe, 'manage-grid-scrolled', fixture, ['--view', 'grid', '--catalogue', cat, '--wheel', '320,520,0,-700'])
writeFileSync(path.join(out, 'comparison.txt'), 'Manage default fixture: exact RGBA equality against master 7a9149e (M4 merged).\n')
