#!/usr/bin/env node

import path from 'node:path'

import {
  loadBundleManifest,
  renderSameOriginBundle,
  writeSameOriginBundle,
} from './render-same-origin-bundle-lib.mjs'

function parseArgs(argv) {
  const options = {
    manifest: '',
    outDir: '',
    stdout: false,
    summary: false,
  }

  for (let index = 0; index < argv.length; index += 1) {
    const argument = argv[index]
    const next = argv[index + 1] || ''

    switch (argument) {
      case '--manifest':
        options.manifest = next
        index += 1
        break
      case '--out-dir':
        options.outDir = next
        index += 1
        break
      case '--stdout':
        options.stdout = true
        break
      case '--summary':
        options.summary = true
        break
      default:
        break
    }
  }

  return options
}

const args = parseArgs(process.argv.slice(2))
const manifestPath = args.manifest || path.resolve(process.cwd(), 'deploy', 'hypertwist.same-origin.bundle.example.json')
const { path: loadedManifestPath, manifest } = loadBundleManifest(manifestPath)

let renderedResult = null
if (args.outDir) {
  renderedResult = writeSameOriginBundle({
    manifest,
    outDir: args.outDir,
  })
} else {
  renderedResult = renderSameOriginBundle(manifest)
}

if (args.summary && renderedResult) {
  process.stdout.write(`${JSON.stringify({
    manifestPath: loadedManifestPath,
    outputDir: renderedResult.outputDir || null,
    validationReport: renderedResult.validationReport,
  }, null, 2)}\n`)
} else if (args.stdout || !args.outDir) {
  process.stdout.write('### website.env\n')
  process.stdout.write(renderedResult.frontendEnvContent)
  process.stdout.write('\n### server.env\n')
  process.stdout.write(renderedResult.serverEnvContent)
  process.stdout.write('\n### systemd\n')
  process.stdout.write(renderedResult.systemdContent)
  process.stdout.write('\n### nginx\n')
  process.stdout.write(renderedResult.nginxContent)
}
