const fs = require('node:fs')
const path = require('node:path')

const frontendRoot = __dirname
const resourceDirectory = path.join(frontendRoot, '..', 'sky_phone')
const sourceDirectory = path.join(frontendRoot, 'dist')
const targetDirectory = path.join(resourceDirectory, 'source', 'html')
const configDefaultPath = path.join(
  resourceDirectory,
  'source',
  'shared',
  'config_default.lua',
)

function readLuaSource(...segments) {
  return fs
    .readFileSync(path.join(resourceDirectory, ...segments), 'utf8')
    .replace(/\r\n?/g, '\n')
    .trimEnd()
}

function generateConfigDefault() {
  const configSource = readLuaSource('config', 'config.lua').replace(
    /\n?-- CONFIG_DEFAULT_EXCLUDE_START[\s\S]*?-- CONFIG_DEFAULT_EXCLUDE_END\n?/g,
    '\n',
  )
  const mediaSource = readLuaSource('config', 'media.lua')
  const generatedSource = [
    '-- GENERATED by frontend/build.cjs from config/config.lua and config/media.lua - do not edit.',
    '-- Escrowed snapshot of the shipped defaults used by the Phone Configurator.',
    'local realConfig = Config',
    'Config = {}',
    '',
    configSource,
    '',
    mediaSource,
    '',
    'ConfigDefaults = Config',
    'Config = realConfig',
    '',
  ].join('\n')

  fs.mkdirSync(path.dirname(configDefaultPath), { recursive: true })
  fs.writeFileSync(configDefaultPath, generatedSource, 'utf8')
  console.log(`Generated Phone Configurator defaults at ${configDefaultPath}`)
}

if (!fs.existsSync(sourceDirectory)) {
  throw new Error(
    'Missing frontend/dist. Run vite build before publishing the NUI.',
  )
}

fs.rmSync(targetDirectory, { force: true, recursive: true })
fs.mkdirSync(targetDirectory, { recursive: true })
fs.cpSync(sourceDirectory, targetDirectory, { recursive: true })

const targetIndex = path.join(targetDirectory, 'index.html')
const normalizedIndex = fs
  .readFileSync(targetIndex, 'utf8')
  .replace(/\r\n?/g, '\n')
  .replace(/\n[ \t]*\n([ \t]*<\/body>)/g, '\n$1')
fs.writeFileSync(targetIndex, normalizedIndex)

generateConfigDefault()
console.log(`Published NUI to ${targetDirectory}`)
