/** Offline M2 UI replay. Every app run is fixture-only with an OS temporary cache. */
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'

const root = path.resolve(import.meta.dir, '..')
const out = path.join(root, 'out/m2b')
const cache = mkdtempSync(path.join(tmpdir(), 'fmm-m2b-'))
mkdirSync(out, { recursive: true })
writeFileSync(path.join(out, 'capture-cache.txt'), cache)
const release = (version: string) => ({ version, released_at: '2026-10-19T00:00:00Z', sha1: '1'.repeat(40), info_json: { factorio_version: '2.0', dependencies: ['base >= 2.0'] } })
const mods = [
  ['new-mod', 'Factory Planner', 'Plan production lines and their dependencies.'],
  ['RateCalculator', 'Rate Calculator', 'Calculate production and consumption rates.'],
  ['bottleneck', 'Bottleneck', 'Show which machines are limiting production.'],
  ['folder-work', 'My local mod', 'A folder mod maintained by hand.'],
].map(([name, title, summary]) => ({ name, title, summary, owner: 'Factorio community', downloads_count: 123456, category: 'utilities', latest_release: release('4.0.0'), releases: [release('4.0.0')] }))
const catalogue = path.join(cache, 'catalogue.json')
writeFileSync(catalogue, JSON.stringify({ results: mods }))
const full = path.join(cache, 'full.json')
writeFileSync(full, JSON.stringify({ ...mods[0], description: 'Plan production lines with the help of required libraries.\n\nDownloads are verified before installation.' }))
const dialog = path.join(cache, 'plan.json')
writeFileSync(dialog, JSON.stringify({ title: 'Confirm installation', lines: ['Install Factory Planner 4.0.0', 'Also installs: Factory Library 1.2.3, Data Helpers 2.0.1', 'Updates: Rate Calculator 4.0.0', 'Optional (not installed): ? graphics-pack >= 1.0', 'Warning: incompatible overhaul is enabled', 'Failed: older-helper: No compatible release for 2.0'], confirm: true }))
const common = ['--fixture', 'crates/app/tests/fixtures/r2b.json', '--size', '1440x945', '--catalogue', catalogue]
const cases: [string, string[]][] = [
  ['explore-download', ['--tab', 'explore', '--explore-select', 'new-mod', '--explore-action-state', 'download', '--portal-full', full]],
  ['explore-update', ['--tab', 'explore', '--explore-select', 'RateCalculator', '--explore-action-state', 'update']],
  ['explore-remove', ['--tab', 'explore', '--explore-select', 'bottleneck', '--explore-action-state', 'remove']],
  ['explore-folder', ['--tab', 'explore', '--explore-select', 'folder-work', '--explore-action-state', 'folder']],
  ['progress', ['--tab', 'explore', '--explore-select', 'new-mod', '--download-progress', 'new-mod=0.46', '--portal-full', full]],
  ['confirm', ['--tab', 'explore', '--confirm-plan', dialog]],
  ['remove-confirm', ['--tab', 'manage', '--remove-confirm', 'Rate Calculator']],
  ['results', ['--tab', 'explore', '--results-banner', '3 mods completed, 1 failed: older-helper: Not on the mirror yet (HTTP 404)']],
  ['updates', ['--tab', 'updates', '--portal-updates', catalogue, '--explore-select', 'RateCalculator', '--explore-action-state', 'update']],
  ['manage', ['--tab', 'manage', '--catalogue', path.join(cache, 'absent.json')]],
]
let log = ''
for (const [name, args] of cases) {
  const result = spawnSync(path.join(root, 'target/release/fmm.exe'), ['--screenshot', path.join(out, `${name}.png`), ...common, ...args], { cwd: root, env: { ...process.env, FMM_CACHE_DIR: cache }, 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
  if (result.status !== 0) throw new Error(log)
  console.log(name)
}
