PLATFORM_ANDROID = 'android'
PLATFORM_IOS = 'ios'

def prepare_source_code_for_js_bundle()
  create_dot_env_file()
  sync_localization_with_poeditor()
end

def create_js_bundle_with_assets_and_sourcemap_for_android()
  create_js_bundle_with_assets_and_sourcemap(
    PLATFORM_ANDROID,
    ANDROID_BUNDLE_FILE,
    ANDROID_ASSETS_DIRECTORY,
    ANDROID_SOURCEMAP_FILE
  )
end

def create_js_bundle_with_assets_and_sourcemap_for_ios()
  create_js_bundle_with_assets_and_sourcemap(
    PLATFORM_IOS,
    IOS_BUNDLE_FILE,
    IOS_ASSETS_DIRECTORY,
    IOS_SOURCEMAP_FILE
  )
end

def create_js_bundle_with_assets_and_sourcemap(
  platform,
  bundle_file_path,
  assets_directory_path,
  source_map_file_path)
  Dir.chdir(root_project_directory_path()) do
    FileUtils.mkdir_p(File.dirname(bundle_file_path))
    FileUtils.mkdir_p(assets_directory_path)
    FileUtils.mkdir_p(File.dirname(source_map_file_path))
    sh(
      'yarn', 'react-native', 'bundle',
      '--platform', platform,
      '--entry-file', 'index.js',
      '--bundle-output', bundle_file_path,
      '--dev', 'false',
      '--assets-dest', assets_directory_path,
      '--sourcemap-output', source_map_file_path,
      '--minify', 'true',
      '--reset-cache'
    )
    compile_hermes_bundle(bundle_file_path, source_map_file_path, platform)
    compose_hermes_sourcemaps(bundle_file_path, source_map_file_path)
  end
end

def compile_hermes_bundle(bundle_file_path, source_map_file_path, platform)
  hermes_cli = if OS.mac?
    'node_modules/react-native/sdks/hermesc/osx-bin/hermesc'
  else
    'node_modules/react-native/sdks/hermesc/linux64-bin/hermesc'
  end

  sh(
    hermes_cli,
    '-emit-binary',
    '-output-source-map',
    '-out', "#{bundle_file_path}.hbc",
    bundle_file_path
  )

  FileUtils.mv("#{bundle_file_path}.hbc", bundle_file_path)
end

def compose_hermes_sourcemaps(bundle_file_path, source_map_file_path)
  hermes_map_path = "#{bundle_file_path}.hbc.map"
  composed_map_path = "#{source_map_file_path}.out"

  unless File.exist?(hermes_map_path)
    raise "Hermes sourcemap not found at #{hermes_map_path}. " \
          "Ensure Hermes compilation completed successfully."
  end

  sh(
    'node',
    'node_modules/react-native/scripts/compose-source-maps.js',
    source_map_file_path,
    hermes_map_path,
    '-o', composed_map_path
  )

  FileUtils.mv(composed_map_path, source_map_file_path)

  FileUtils.rm_f(hermes_map_path)
end


def test_android_js_bundle()
  test_js_bundle(ANDROID_BUNDLE_FILE)
end

def test_ios_js_bundle()
  test_js_bundle(IOS_BUNDLE_FILE)
end

def test_js_bundle(bundle_file_path)
  full_file_path = "#{root_project_directory_path()}/#{bundle_file_path}"
  sh "yarn test:js:bundle #{full_file_path}"
end
