import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { LuaFactory } from 'wasmoon'
import { DEFAULT_INSTALL_DIRS, readGameVersion } from '../src/core/paths'
import { inheritStyles, type Style, type StyleDump } from '../src/core/gameStyle'

// findFactorio also inspects the user's config; extraction must only read the install.
export function styleInstall(): string {
  const candidates = process.env.FACTORIO_DIR ? [process.env.FACTORIO_DIR] : DEFAULT_INSTALL_DIRS
  const install = candidates.find(dir => existsSync(path.join(dir, 'data/core/prototypes/style.lua')))
  if (!install) throw new Error('Factorio install not found (set FACTORIO_DIR)')
  return path.resolve(install)
}

function sorted(value: unknown): unknown {
  if (Array.isArray(value)) return value.map(sorted)
  if (value && typeof value === 'object') {
    return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, sorted(v)]))
  }
  return value
}

export async function dumpStyles(install: string): Promise<StyleDump> {
  const core = path.join(install, 'data/core')
  const lua = await new LuaFactory().createEngine()
  try {
    lua.global.set('module_source', (name: string) => {
      if (!/^[\w-]+(?:\.[\w-]+)*$/.test(name)) throw new Error(`Unsupported Lua module: ${name}`)
      return readFileSync(path.join(core, 'lualib', name.replaceAll('.', '/') + '.lua'), 'utf8')
    })
    await lua.doString(`
      io = nil
      os = nil
      dofile = nil
      loadfile = nil
      package = nil
      defines = {direction = {}}
      local directions = {'north', 'northnortheast', 'northeast', 'eastnortheast',
        'east', 'eastsoutheast', 'southeast', 'southsoutheast', 'south',
        'southsouthwest', 'southwest', 'westsouthwest', 'west', 'westnorthwest',
        'northwest', 'northnorthwest'}
      for i, name in ipairs(directions) do defines.direction[name] = i - 1 end
      local loaded = {}
      function require(name)
        if loaded[name] ~= nil then return loaded[name] end
        local result = assert(load(module_source(name), '@' .. name))()
        loaded[name] = result == nil and true or result
        return loaded[name]
      end
      data = {raw = {}}
      function data:extend(prototypes)
        for _, prototype in ipairs(prototypes) do
          self.raw[prototype.type] = self.raw[prototype.type] or {}
          self.raw[prototype.type][prototype.name] = prototype
        end
      end
      require('util')
      baseline = {}
      for key in pairs(_G) do baseline[key] = true end
    `)
    await lua.doString(readFileSync(path.join(core, 'prototypes/style.lua'), 'utf8'))
    await lua.doString(readFileSync(path.join(core, 'prototypes/fonts.lua'), 'utf8'))
    await lua.doString(`
      style_constants = {}
      for key, value in pairs(_G) do
        if not baseline[key] and key ~= 'style_constants' and type(value) ~= 'function' then
          style_constants[key] = value
        end
      end
      style_prototype = data.raw['gui-style'].default
      style_fonts = data.raw.font
    `)
    const prototype = lua.global.get('style_prototype') as Record<string, unknown>
    const constants = lua.global.get('style_constants') as Record<string, unknown>
    const raw: Record<string, Style> = {}
    for (const [name, value] of Object.entries(prototype)) {
      if (value && typeof value === 'object' && (value as Style).type?.endsWith('_style')) raw[name] = value as Style
      else if (name !== 'type' && name !== 'name') constants[name] = value
    }
    const fonts = lua.global.get('style_fonts') as Record<string, Style>
    const locale = JSON.parse(readFileSync(path.join(core, 'locale/en/info.json'), 'utf8')) as { font: Record<string, string[]> }
    for (const font of Object.values(fonts)) {
      const files = typeof font.from === 'string' ? locale.font[font.from] : undefined
      if (files) {
        font.files = files
        font.filename = files[0]
        font.weight = files[0]?.includes('SemiBold') ? 600 : files[0]?.includes('Bold') ? 700 : 400
      }
    }
    return {
      gameVersion: readGameVersion(install),
      raw,
      resolved: inheritStyles(raw),
      constants,
      fonts,
    }
  } finally {
    lua.global.close()
  }
}

if (import.meta.main) {
  const dump = await dumpStyles(styleInstall())
  mkdirSync('assets/game', { recursive: true })
  writeFileSync('assets/game/styles.json', JSON.stringify(sorted(dump), null, 2) + '\n')
  console.log(`[dump-styles] ${Object.keys(dump.raw).length} styles, ${Object.keys(dump.fonts).length} fonts (game ${dump.gameVersion})`)
}
