# encoding: utf-8

Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8

lane :app_store_connect_check_exists do
  apple_id = ENV['FASTLANE_USER']
  apple_id_password = ENV['FASTLANE_PASSWORD']
  developer_team_id = ENV['APP_STORE_CONNECT_DEVELOPER_TEAM_ID']
  app_identifier = ENV['APP_IDENTIFIER']
  ios_sku = ENV['IOS_SKU']
  team_name = ENV['APP_STORE_CONNECT_TEAM_NAME']
  app_name = ENV['APP_TITLE']
  app_default_language = ENV['APP_DEFAULT_LANGUAGE']

  begin
    Spaceship::Tunes.login(apple_id, apple_id_password)
    spaceship_app = Spaceship::Tunes::Application.find(app_identifier)
    if spaceship_app.nil?
      create_app_online(
        username: apple_id,
        app_identifier: app_identifier,
        app_name: app_name,
        language: app_default_language,
        sku: ios_sku,
        platforms: ["ios"],
        team_id: developer_team_id,
        itc_team_name: team_name,
      )
    else
      puts "App already exists in App Store Connect"
    end
  rescue => ex
    # Log the error message
    puts "Error while creating the app: #{ex.message}"
  ensure
    puts "Creating app completed."
  end

end

lane :app_store_connect_update do
  apple_id = ENV['APPLE_ID']
  app_identifier = ENV['APP_IDENTIFIER']
  team_name = ENV['APP_STORE_CONNECT_TEAM_NAME']

  begin
    modify_services(
      username: apple_id,
      app_identifier: app_identifier,
      team_name: team_name,
      services: {
        "push_notification": "on"
      }
    )
  rescue => ex
    # Log the error message
    puts "Error while modifying services: #{ex.message}"
  ensure
    puts "Modify services process completed."
  end

  begin
    upload_app_privacy_details_to_app_store(
      username: apple_id,
      app_identifier: app_identifier,
      team_name: team_name,
      json_path: "fastlane/metadata/app_privacy.json"
    )
  rescue => ex
    puts "Error while uploading app privacy details: #{ex.message}"
  ensure
    puts "Upload app privacy details process completed."
  end
end

def log_ios_signing_debug(keychain_name, label)
  UI.message("🔍 [#{label}] Code signing identities in temp keychain:")
  identities = `security find-identity -v -p codesigning "#{keychain_name}" 2>&1`
  UI.message(identities.empty? ? "(no output)" : identities)

  UI.message("🔍 [#{label}] User keychain search list:")
  keychains = `security list-keychains -d user 2>&1`
  UI.message(keychains.empty? ? "(no output)" : keychains)

  if Dir.exist?("./builds")
    UI.message("🔍 [#{label}] ios/builds contents:")
    UI.message(Dir.entries("./builds").join(", "))
  end
end

def configure_keychain_for_codesign(keychain_name, keychain_password)
  UI.message("🔐 Setting key partition list for codesign tools...")
  begin
    sh("security", "set-key-partition-list", "-S", "apple-tool:,apple:,codesign:", "-s", "-k", keychain_password, keychain_name)
    UI.message("✅ Key partition list updated.")
  rescue => e
    UI.message("ℹ️ set-key-partition-list skipped: #{e.message}")
  end
end

def distribution_code_sign_identity(keychain_name)
  identities = `security find-identity -v -p codesigning "#{keychain_name}" 2>&1`
  if identities.include?("Apple Distribution")
    UI.message("ℹ️ Using code sign identity: Apple Distribution")
    "Apple Distribution"
  elsif identities.include?("iPhone Distribution")
    UI.message("ℹ️ Using code sign identity: iPhone Distribution")
    "iPhone Distribution"
  else
    UI.user_error!("No Apple/iPhone Distribution identity in keychain after match.\n#{identities}")
  end
end

def match_appstore_profile_name(app_identifier)
  env_key = "sigh_#{app_identifier}_appstore_profile-name"
  profile_name = ENV[env_key]
  if profile_name.nil? || profile_name.empty?
    profile_name_file = File.join(ENV["FULL_PROJECT_DIR"].to_s, "ios/builds/match-appstore-profile-name.txt")
    if File.exist?(profile_name_file)
      profile_name = File.read(profile_name_file).strip
    end
  end
  if profile_name.nil? || profile_name.empty?
    "match AppStore #{app_identifier}"
  else
    profile_name
  end
end

def apply_runner_release_signing(app_identifier, developer_team_id, distribution_identity)
  profile_name = match_appstore_profile_name(app_identifier)
  UI.message("🚀 Applying manual Release signing (identity=#{distribution_identity}, profile=#{profile_name})...")
  update_code_signing_settings(
    profile_name: profile_name,
    build_configurations: "Release",
    code_sign_identity: distribution_identity,
    use_automatic_signing: false,
    targets: "Runner",
  )
  update_project_team(
    teamid: developer_team_id
  )
end

def run_pod_unbundled(*args)
  sh(
    "env",
    "-u", "BUNDLE_GEMFILE",
    "-u", "BUNDLE_PATH",
    "-u", "BUNDLE_USER_HOME",
    "asdf", "exec", "pod",
    *args
  )
end

def pod_version_unbundled
  `env -u BUNDLE_GEMFILE -u BUNDLE_PATH -u BUNDLE_USER_HOME asdf exec pod --version 2>&1`.strip
end

lane :build_ios_pre do
  full_project_dir = ENV["FULL_PROJECT_DIR"]
  if full_project_dir == nil
      UI.user_error!("Environment variable FULL_PROJECT_DIR is missing.")
  end
  ios_dir = full_project_dir + "/ios"
  UI.message("ℹ️ The directory of the current application is: #{full_project_dir}")

  build_number = ENV["NEW_BUILD"]
  version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]

  default_keychain_name = ENV['DEFAULT_KEYCHAIN_NAME']
  default_keychain_password = ENV['DEFAULT_KEYCHAIN_PASSWORD']
  import_certificate_path = "./AppleWWDRCA.cer"

  developer_team_id = ENV['APP_STORE_CONNECT_DEVELOPER_TEAM_ID']

  app_store_key_id = ENV['APP_STORE_CONNECT_KEY_ID']
  app_store_issuer_id = ENV['APP_STORE_CONNECT_KEY_ISSUER_ID']
  app_store_key_path = ENV['APP_STORE_CONNECT_KEY_PATH']

  app_identifier = ENV['IOS_APP_IDENTIFIER']

  match_ssh_key_path = ENV['FASTLANE_MATCH_BOT_SSH_KEY_PATH']
  match_git_username = ENV['FASTLANE_MATCH_BOT_USERNAME']
  match_git_fullname = ENV['FASTLANE_MATCH_BOT_FULLNAME']
  match_git_email = ENV['FASTLANE_MATCH_BOT_EMAIL']
  match_git_url = ENV['FASTLANE_MATCH_GIT_HTTP_URL']
  match_git_basic_authorization = ENV['FASTLANE_MATCH_GIT_BASIC_AUTHORIZATION']
  if match_git_url.nil? || match_git_url.empty?
    match_git_path = ENV['FASTLANE_MATCH_GITLAB_PROJECT_PATH']
    if match_git_path.nil? || match_git_path.empty?
      UI.user_error!("Environment variable FASTLANE_MATCH_GIT_HTTP_URL or FASTLANE_MATCH_GITLAB_PROJECT_PATH is missing.")
    end
    match_git_url = "https://gitlab.application-platform.com/#{match_git_path}.git"
  end
  use_https_match = !match_git_basic_authorization.nil? && !match_git_basic_authorization.empty?

  if build_number == nil
    UI.user_error!("Environment variable NEW_BUILD is missing.")
  end
  if version_number == nil
    UI.user_error!("Environment variable NEW_VERSION is missing.")
  end

  if default_keychain_name == nil
    UI.user_error!("Environment variable DEFAULT_KEYCHAIN_NAME is missing.")
  end
  if default_keychain_password == nil
    UI.user_error!("Environment variable DEFAULT_KEYCHAIN_PASSWORD is missing.")
  end
  if import_certificate_path == nil
    UI.user_error!("Environment variable IMPORT_CERTIFICATE_PATH is missing.")
  end

  if developer_team_id == nil
    UI.user_error!("Environment variable APP_STORE_CONNECT_DEVELOPER_TEAM_ID is missing.")
  end
  if app_store_key_id == nil
    UI.user_error!("Environment variable APP_STORE_CONNECT_KEY_ID is missing.")
  end
  if app_store_issuer_id == nil
    UI.user_error!("Environment variable APP_STORE_CONNECT_KEY_ISSUER_ID is missing.")
  end
  if app_store_key_path == nil
    UI.user_error!("Environment variable APP_STORE_CONNECT_KEY_PATH is missing.")
  end
  if app_identifier == nil
    UI.user_error!("Environment variable IOS_APP_IDENTIFIER is missing.")
  end
  if use_https_match
    if match_git_basic_authorization == nil || match_git_basic_authorization.empty?
      UI.user_error!("Environment variable FASTLANE_MATCH_GIT_BASIC_AUTHORIZATION is missing.")
    end
    if match_git_email == nil || match_git_email.empty?
      UI.user_error!("Environment variable FASTLANE_MATCH_BOT_EMAIL is missing.")
    end
  elsif match_ssh_key_path == nil
    UI.user_error!("Environment variable FASTLANE_MATCH_BOT_SSH_KEY_PATH is missing.")
  end
  if match_git_username == nil
    UI.user_error!("Environment variable FASTLANE_MATCH_BOT_USERNAME is missing.")
  end
  if match_git_fullname == nil
    UI.user_error!("Environment variable FASTLANE_MATCH_BOT_FULLNAME is missing.")
  end

  UI.message("🚀 Unlocking keychain and importing certificates...")
  UI.message("ℹ️ Temp keychain path: #{default_keychain_name}")
  unlock_keychain(
    path: default_keychain_name,
    password: default_keychain_password,
    add_to_search_list: true,
    set_default: true
  )
  log_ios_signing_debug(default_keychain_name, "after unlock_keychain")

  UI.message("🚀 Importing Apple WWDRCA certificate...")
  import_certificate(
    certificate_path: import_certificate_path,
    keychain_name: default_keychain_name,
    keychain_password: default_keychain_password,
    log_output: true
  )

  UI.message("🚀 Syncing code signing for app identifier #{app_identifier}...")
  api_key = app_store_connect_api_key(
    key_id: app_store_key_id,
    issuer_id: app_store_issuer_id,
    key_filepath: app_store_key_path,
    duration: 1200, # optional (maximum 1200)
    in_house: false # optional but may be required if using match/sigh
  )

  max_retries = 3
  attempt = 0

  begin
    attempt += 1
    UI.message("🚀 Syncing certificates and profiles from match repository... (Versuch #{attempt}/#{max_retries})")
    match_options = {
      api_key: api_key,
      type: "appstore",
      app_identifier: app_identifier,
      readonly: false,
      output_path: "./builds",
      keychain_name: default_keychain_name,
      keychain_password: default_keychain_password,
      team_id: developer_team_id,
      git_branch: developer_team_id,
      git_url: match_git_url,
      git_full_name: match_git_fullname,
      storage_mode: "git",
      verbose: true
    }
    if use_https_match
      match_options[:git_basic_authorization] = match_git_basic_authorization
      match_options[:git_user_email] = match_git_email
    else
      match_options[:git_private_key] = match_ssh_key_path
      match_options[:git_user_email] = match_git_username
    end
    sync_code_signing(**match_options)
  rescue => e
    if attempt < max_retries
      UI.error("❌ Fehler beim Sync (Versuch #{attempt}): #{e.message}")
      UI.message("🔁 Neuer Versuch in 5 Sekunden...")
      sleep 5
      retry
    else
      UI.user_error!("🚨 Sync ist nach #{max_retries} Versuchen fehlgeschlagen: #{e.message}")
    end
  end

  configure_keychain_for_codesign(default_keychain_name, default_keychain_password)
  log_ios_signing_debug(default_keychain_name, "after match sync")
  distribution_identity = distribution_code_sign_identity(default_keychain_name)

  profile_name = match_appstore_profile_name(app_identifier)
  profile_name_file = File.join(ios_dir, "builds/match-appstore-profile-name.txt")
  FileUtils.mkdir_p(File.dirname(profile_name_file))
  File.write(profile_name_file, profile_name)
  UI.message("ℹ️ Saved match profile name to #{profile_name_file}")

  # Set App Details
  UI.message("🚀 Setting up Xcode project...")
  apply_runner_release_signing(app_identifier, developer_team_id, distribution_identity)

  update_app_identifier(
    app_identifier: app_identifier,
    plist_path: "Runner/Info.plist"
  )

  # Set App Version Code (should be the date time generated file)
  increment_build_number(
    build_number: build_number,
    xcodeproj: "Runner.xcodeproj"
  )

  # Set App Version Name
  increment_version_number(
    version_number: version_number,
    xcodeproj: "Runner.xcodeproj"
  )

  # Create App Icons
  appicon(
    appicon_devices: [:ipad, :iphone, :ios_marketing],
    appicon_path: "Runner/Assets.xcassets",
    appicon_image_file: "fastlane/metadata/app_icon.png"
  )

  Dir.chdir(full_project_dir) do
    UI.message("🚀 Running Flutter pub get...")
    sh("asdf", "exec", "flutter", "pub", "get")
  end

  Dir.chdir(ios_dir) do
    UI.message("🚀 Ensuring CocoaPods CLI is available...")
    pod_check = pod_version_unbundled
    pod_ok = $?.success?
    unless pod_ok
      UI.message("ℹ️ pod not available (#{pod_check}), installing cocoapods gem...")
      sh("asdf", "exec", "gem", "install", "cocoapods", "--no-document")
      sh("asdf", "reshim", "ruby")
      pod_check = pod_version_unbundled
      pod_ok = $?.success?
      unless pod_ok
        UI.user_error!("CocoaPods still unavailable after gem install: #{pod_check}")
      end
    end
    UI.message("ℹ️ Using CocoaPods #{pod_check}")

    UI.message("🚀 Running pod install --repo-update...")
    run_pod_unbundled("install", "--repo-update")
    UI.message("✅ pod install completed.")
  end

  # pod install can reset signing — re-apply Release signing for Runner.
  apply_runner_release_signing(app_identifier, developer_team_id, distribution_identity)
  configure_keychain_for_codesign(default_keychain_name, default_keychain_password)
  log_ios_signing_debug(default_keychain_name, "after pod install")
end

lane :build_ios_export do
  default_keychain_name = ENV['DEFAULT_KEYCHAIN_NAME']
  default_keychain_password = ENV['DEFAULT_KEYCHAIN_PASSWORD']
  app_identifier = ENV['IOS_APP_IDENTIFIER']
  developer_team_id = ENV['APP_STORE_CONNECT_DEVELOPER_TEAM_ID']
  export_options_plist = ENV['IOS_EXPORT_OPTIONS_PLIST']

  if default_keychain_name == nil || default_keychain_name.empty?
    UI.user_error!("Environment variable DEFAULT_KEYCHAIN_NAME is missing.")
  end
  if default_keychain_password == nil || default_keychain_password.empty?
    UI.user_error!("Environment variable DEFAULT_KEYCHAIN_PASSWORD is missing.")
  end
  if app_identifier == nil || app_identifier.empty?
    UI.user_error!("Environment variable IOS_APP_IDENTIFIER is missing.")
  end
  if developer_team_id == nil || developer_team_id.empty?
    UI.user_error!("Environment variable APP_STORE_CONNECT_DEVELOPER_TEAM_ID is missing.")
  end
  if export_options_plist == nil || export_options_plist.empty?
    UI.user_error!("Environment variable IOS_EXPORT_OPTIONS_PLIST is missing.")
  end
  unless File.exist?(export_options_plist)
    UI.user_error!("ExportOptions.plist not found at #{export_options_plist}")
  end

  full_project_dir = ENV["FULL_PROJECT_DIR"]
  if full_project_dir.nil? || full_project_dir.empty?
    UI.user_error!("Environment variable FULL_PROJECT_DIR is missing.")
  end

  archive_path = File.join(full_project_dir, "build/ios/archive/Runner.xcarchive")
  unless File.directory?(archive_path)
    UI.user_error!("Expected archive at #{archive_path}. Run xcodebuild archive first.")
  end

  profile_name = match_appstore_profile_name(app_identifier)
  UI.message("🔍 Export archive: #{archive_path}")
  UI.message("🔍 ExportOptions.plist: #{export_options_plist}")
  UI.message("🔍 Provisioning profile: #{profile_name}")

  unlock_keychain(
    path: default_keychain_name,
    password: default_keychain_password,
    add_to_search_list: true,
    set_default: true
  )
  configure_keychain_for_codesign(default_keychain_name, default_keychain_password)
  log_ios_signing_debug(default_keychain_name, "before export")

  distribution_identity = distribution_code_sign_identity(default_keychain_name)
  apply_runner_release_signing(app_identifier, developer_team_id, distribution_identity)
  log_ios_signing_debug(default_keychain_name, "after re-apply signing before export")

  UI.message("🚀 Exporting signed IPA from archive...")
  build_app(
    suppress_xcode_output: false,
    silent: false,
    export_team_id: developer_team_id,
    skip_build_archive: true,
    archive_path: archive_path,
    output_directory: "./builds",
    output_name: "Runner.ipa",
    export_method: "app-store",
    export_options: {
      method: "app-store",
      signingStyle: "manual",
      teamID: developer_team_id,
      provisioningProfiles: {
        app_identifier => profile_name
      }
    }
  )
  UI.message("✅ Signed IPA exported to ./builds/Runner.ipa")
end

lane :build_ios_post do
  build_ios_export
end

def resolved_changelog
  changelog = ENV["NEW_CHANGELOG"]
  if changelog.nil?
    UI.user_error!("Environment variable NEW_CHANGELOG is missing.")
  elsif changelog.strip.empty?
    version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]
    build_number = ENV["NEW_BUILD"]
    changelog = "Release #{version_number} (build #{build_number})"
    UI.message("ℹ️ Empty changelog — using default release notes: #{changelog}")
  end
  changelog
end

lane :publish_ios_firebase do
  changelog = resolved_changelog
  build_number = ENV["NEW_BUILD"]
  version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]
  app_identifier = ENV['IOS_APP_IDENTIFIER']
  firebase_app_id_ios = ENV['FIREBASE_APP_ID_IOS']

  if build_number == nil or build_number.strip == ""
    UI.user_error!("Environment variable NEW_BUILD is missing.")
  end
  if version_number == nil or version_number.strip == ""
    UI.user_error!("Environment variable NEW_VERSION is missing.")
  end
  if app_identifier == nil or app_identifier.strip == ""
    UI.user_error!("Environment variable IOS_APP_IDENTIFIER is missing.")
  end
  if firebase_app_id_ios == nil or firebase_app_id_ios.strip == ""
    UI.user_error!("Environment variable FIREBASE_APP_ID_IOS is missing.")
  end

  UI.message("🚀 Publishing iOS version #{version_number} (build #{build_number}) to Firebase...")

  firebase_app_distribution(
    service_credentials_file: "../firebase-service-account.json",
    ipa_path: "./builds/Runner.ipa",
    app: firebase_app_id_ios,
    testers: "robin.janke@doppelt-digital.de",
    release_notes: changelog
  )
end

lane :publish_ios do
  if ENV['FIREBASE_APP_ID_IOS'] && !ENV['FIREBASE_APP_ID_IOS'].strip.empty?
    publish_ios_firebase
  else
    UI.message("ℹ️ FIREBASE_APP_ID_IOS not set — skipping Firebase App Distribution.")
  end

  changelog = resolved_changelog
  key_id = ENV['APP_STORE_CONNECT_KEY_ID']
  issuer_id = ENV['APP_STORE_CONNECT_KEY_ISSUER_ID']
  key_filepath = ENV['APP_STORE_CONNECT_KEY_PATH']
  build_number = ENV["NEW_BUILD"]
  version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]
  app_identifier = ENV['IOS_APP_IDENTIFIER']

  if ENV['CREATE_NEW_SCREENSHOTS'] == "true"
    upload_screenshots = true
  else
    upload_screenshots = false
  end

  if ENV['TEST_CHANGED'] == "true"
    test_changed = true
  end

  if key_id == nil or key_id.strip() == ""
    UI.user_error!("Environment variable APP_STORE_CONNECT_KEY_ID is missing.")
  end
  if issuer_id == nil or issuer_id.strip() == ""
    UI.user_error!("Environment variable APP_STORE_CONNECT_KEY_ISSUER_ID is missing.")
  end
  if key_filepath == nil or key_filepath.strip() == ""
    UI.user_error!("Environment variable APP_STORE_CONNECT_KEY_PATH is missing.")
  end

  api_key = app_store_connect_api_key(
    key_id: key_id,
    issuer_id: issuer_id,
    key_filepath: key_filepath,
    duration: 1200,
    in_house: false
  )

  UI.message("🚀 Publishing iOS version #{version_number} (build #{build_number}) to Test Flight...")

  upload_to_testflight(
    ipa: "./builds/Runner.ipa",
    changelog: changelog,
    skip_waiting_for_build_processing: false,
    # groups: ["Externe Tester"],
    # testers_file_path: "./fastlane/testflight-user.csv",
    skip_submission: false,
    expire_previous_builds: true,
    distribute_external: false,
    notify_external_testers: false,
    beta_app_description: "Dies ist ein Vorab-Test einer doppelt.digital App.",
    beta_app_feedback_email: "kontakt@doppelt-digital.de",
    api_key: api_key,
    beta_app_review_info: {
      contact_email: "robin.janke@doppelt-digital.de",
      contact_first_name: "Robin",
      contact_last_name: "Janke",
      contact_phone: "+4915232060755",
      notes: "Das ist die Vorab-Demo-Version der App.",
    },
    localized_app_info: {
      "default": {
        feedback_email: "kontakt@doppelt-digital.de",
        marketing_url: "https://www.doppelt-digital.de",
        privacy_policy_url: "https://www.doppelt-digital.de/datenschutz",
        description: "Dies ist ein Vorab-Test einer doppelt.digital App.",
      }
    },
    localized_build_info: {
      "default": {
        whats_new: changelog,
      }
    }
  )

  UI.message("🚀 Publishing Metadata of iOS version #{version_number} (build #{build_number}) to App Store Connect...")

  upload_to_app_store(
    # Upload without generating a HTML report first
    force: true,

    # Screenshots
    skip_screenshots: !upload_screenshots,
    sync_screenshots: upload_screenshots,
    screenshots_path: "fastlane/screenshots",
    overwrite_screenshots: false,
    screenshot_processing_timeout: 180,

    # App Details
    app_identifier: app_identifier,
    app_version: version_number,
    build_number: build_number,

    # Price
    # price_tier: 0,

    # Metadata
    skip_metadata: false,
    skip_app_version_update: false,
    app_icon: "Runner/Assets.xcassets/AppIcon.appiconset",
    app_rating_config_path: "fastlane/metadata/app_rating_config.json",
    copyright: "#{Time.now.year} doppelt.digital",
    submission_information: {
      # IDFA
      add_id_info_uses_idfa: true,

      # Export Compliance
      export_compliance_compliance_required: false,
      export_compliance_encryption_updated: false,
      export_compliance_app_type: nil,
      export_compliance_uses_encryption: false,
      export_compliance_is_exempt: false,
      export_compliance_contains_third_party_cryptography: false,
      export_compliance_contains_proprietary_cryptography: false,

      # Content Rights
      content_rights_contains_third_party_content: true,
      content_rights_has_rights: true
    },

    # Release App
    skip_binary_upload: true,
    automatic_release: true,
    submit_for_review: false,
    reject_if_possible: false,
    use_live_version: false,

    # Precheck
    precheck_include_in_app_purchases: false,
    run_precheck_before_submit: true
  )
end

lane :store_review_ios do
  key_id = ENV['APP_STORE_CONNECT_KEY_ID']
  issuer_id = ENV['APP_STORE_CONNECT_KEY_ISSUER_ID']
  key_filepath = ENV['APP_STORE_CONNECT_KEY_PATH']
  build_number = ENV["NEW_BUILD"]
  version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]
  app_identifier = ENV['IOS_APP_IDENTIFIER']

  api_key = app_store_connect_api_key(
    key_id: key_id,
    issuer_id: issuer_id,
    key_filepath: key_filepath,
    duration: 1200, # optional (maximum 1200)
    in_house: false # optional but may be required if using match/sigh
  )

  upload_to_app_store(
    submit_for_review: true,
    automatic_release: true,
    force: true, # Skip HTMl report verification
    skip_metadata: true,
    skip_screenshots: true,
    skip_binary_upload: true,

    # App Details
    app_identifier: app_identifier,
    app_version: version_number,
    build_number: build_number,

    api_key: api_key,

    # Precheck
    precheck_include_in_app_purchases: false,
    run_precheck_before_submit: true
  )
end