default_platform(:android)

platform :android do
  desc "Publish the localized store listing (copy, graphics and screenshots) for every language"
  lane :upload_listing do
    # supply uploads whatever locale folders it finds, and PUTting a listing creates the language
    # on Play, so a folder added since the last run is all it takes to open a new store listing.
    # It fails part-way through the locale list on overlong copy or a half-populated folder,
    # though, which leaves the listing inconsistent - so the folders are validated first.
    check = sh(
      "python3", "../scripts/check_store_listings.py", "--quiet",
      error_callback: ->(result) { UI.user_error!("Store listing check failed, see above.") },
    )
    UI.message(check)

    upload_to_play_store(
      skip_upload_apk: true,
      skip_upload_aab: true,
      skip_upload_changelogs: true,
      # The listing icon and feature graphic live in en-US/images and are the only graphics Play
      # keeps at the default-language level, so this lane owns them too.
      skip_upload_images: false,
      skip_upload_screenshots: false,
      skip_upload_metadata: false,
    )
  end

  desc "Deprecated alias for upload_listing"
  lane :upload_screenshots do
    upload_listing
  end

  desc "Deploy AAB to Play Store production"
  lane :deploy do
    upload_to_play_store(
      track: 'production',
      aab: 'androidApp/build/outputs/bundle/playStoreRelease/androidApp-playStore-release.aab',
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true,
    )
  end
end

platform :ios do
  desc "Replace the App Store screenshots of the version that is open for editing"
  lane :upload_screenshots do |options|
    app_store_connect_api_key(
      key_id: ENV.fetch("ASC_KEY_ID"),
      issuer_id: ENV.fetch("ASC_ISSUER_ID"),
      key_filepath: File.expand_path("~/.appstoreconnect/private_keys/AuthKey_#{ENV.fetch('ASC_KEY_ID')}.p8"),
      in_house: false,
    )

    screenshots_path = File.expand_path("screenshots", __dir__)
    if Dir.glob(File.join(screenshots_path, "*", "*.png")).empty?
      UI.user_error!("No screenshots in #{screenshots_path}. Run './gradlew :screenshotTests:generateIosStoreScreenshots' first.")
    end

    # Screenshots belong to an App Store version, so one has to be editable. Passing version:X.Y.Z
    # creates it; without it we only touch a version that already exists and has not been submitted.
    app_version = options[:version]
    if app_version.nil?
      app = Spaceship::ConnectAPI::App.find(CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier))
      edit_version = app&.get_edit_app_store_version(platform: Spaceship::ConnectAPI::Platform::IOS)
      if edit_version.nil?
        UI.user_error!("No App Store version is open for editing. Pass version:X.Y.Z to create one, or run this before 'fastlane ios deploy' submits the release.")
      end
      UI.message("Uploading screenshots to version #{edit_version.version_string}")
    end

    upload_to_app_store(
      app_version: app_version,
      screenshots_path: screenshots_path,
      # deliver validates the metadata directory even when skip_metadata is set, and the default
      # fastlane/metadata holds the android and ios trees rather than locale folders.
      metadata_path: File.expand_path("metadata/ios", __dir__),
      skip_binary_upload: true,
      skip_metadata: true,
      skip_screenshots: false,
      overwrite_screenshots: true,
      submit_for_review: false,
      run_precheck_before_submit: false,
      force: true,
    )
  end

  desc "Pull the live App Store listing into fastlane/metadata/ios to inspect it locally (not committed)"
  lane :download_metadata do
    app_store_connect_api_key(
      key_id: ENV.fetch("ASC_KEY_ID"),
      issuer_id: ENV.fetch("ASC_ISSUER_ID"),
      key_filepath: File.expand_path("~/.appstoreconnect/private_keys/AuthKey_#{ENV.fetch('ASC_KEY_ID')}.p8"),
      in_house: false,
    )

    require "deliver"
    require "deliver/options"
    require "deliver/runner"
    require "deliver/setup"
    options = FastlaneCore::Configuration.create(
      Deliver::Options.available_options,
      {
        app_identifier: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier),
        metadata_path: File.expand_path("metadata/ios", __dir__),
        skip_binary_upload: true,
        skip_screenshots: true,
        run_precheck_before_submit: false,
        force: true,
      },
    )
    Deliver::Runner.new(options, { app_identifier: false, app_version: true, ipa: true, pkg: true })
    app = Deliver.cache[:app]
    version = app.get_latest_app_store_version(platform: Spaceship::ConnectAPI::Platform::IOS)
    # release_notes.txt describes the release being prepared, which /release writes and the deploy
    # lane reads. Downloading would replace it with the notes of the version already on sale, in
    # every locale, so all of them are saved and restored.
    pending_notes = Dir.glob(File.join(options[:metadata_path], "*", "release_notes.txt"))
                       .to_h { |path| [path, File.read(path)] }

    Deliver::Setup.new.generate_metadata_files(app, version, options[:metadata_path], options)

    pending_notes.each { |path, text| File.write(path, text) }

    # The download also writes the App Store review contact (name, email, phone number) and demo
    # credentials. This repository is public, so those are dropped again straight away. deliver
    # skips metadata files that do not exist, so App Store Connect keeps the values already set.
    FileUtils.rm_rf(File.join(options[:metadata_path], "review_information"))

    UI.important("The listing text is git-ignored on purpose: App Store Connect owns it. Delete these")
    UI.important("files again when you are done, otherwise 'fastlane ios deploy' will push them back.")
  end

  desc "Build, archive, upload to App Store Connect, submit for review, auto-release"
  lane :deploy do
    app_store_connect_api_key(
      key_id: ENV.fetch("ASC_KEY_ID"),
      issuer_id: ENV.fetch("ASC_ISSUER_ID"),
      key_filepath: File.expand_path("~/.appstoreconnect/private_keys/AuthKey_#{ENV.fetch('ASC_KEY_ID')}.p8"),
      in_house: false,
    )
    metadata_path = File.expand_path("metadata/ios", __dir__)
    release_notes = collect_release_notes(metadata_path)
    verify_every_store_locale_has_release_notes(release_notes)

    build_app(
      project: "iosApp/iosApp.xcodeproj",
      scheme: "iosApp",
      configuration: "Release",
      export_method: "app-store",
      export_options: "iosApp/ExportOptions.plist",
      output_directory: "build/ios",
      clean: true,
      xcargs: "-allowProvisioningUpdates",
    )
    upload_to_testflight(
      # TestFlight has a single changelog, so testers get the default language.
      changelog: release_notes.fetch("en-US"),
      skip_submission: true,
      skip_waiting_for_build_processing: false,
    )
    upload_to_app_store(
      metadata_path: metadata_path,
      screenshots_path: File.expand_path("screenshots", __dir__),
      release_notes: release_notes,
      skip_binary_upload: true,
      # A new App Store version inherits the previous one's screenshots, so every release replaces
      # the whole set rather than adding to it.
      skip_screenshots: false,
      overwrite_screenshots: true,
      skip_metadata: false,
      submit_for_review: true,
      automatic_release: true,
      force: true,
      precheck_include_in_app_purchases: false,
      submission_information: {
        export_compliance_uses_encryption: false,
        content_rights_contains_third_party_content: false,
        add_id_info_uses_idfa: false,
      },
    )
  end
end

# "What's New" for every App Store language, keyed by locale. Only release_notes.txt is tracked in
# git under fastlane/metadata/ios - the rest of the listing lives in App Store Connect - so the
# locale folders present here are exactly the ones with notes.
def collect_release_notes(metadata_path)
  notes = Dir.glob(File.join(metadata_path, "*", "release_notes.txt")).sort.to_h do |path|
    text = File.read(path).strip
    if text.empty?
      UI.user_error!("Release notes are empty: #{path}. Run /release (it writes every locale), or fill the file in by hand.")
    end
    [File.basename(File.dirname(path)), text]
  end

  unless notes.key?("en-US")
    UI.user_error!("Release notes missing: #{File.join(metadata_path, 'en-US', 'release_notes.txt')}. Run /release first (it writes this file), or create it manually with the 'What's New' text.")
  end
  notes
end

# App Store Connect rejects an update whose localizations do not all have "What's New", and a
# language added in the web UI arrives here with no release_notes.txt at all. Catch that before the
# archive rather than half an hour later at submission.
def verify_every_store_locale_has_release_notes(release_notes)
  app = Spaceship::ConnectAPI::App.find(CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier))
  version = app&.get_edit_app_store_version(platform: Spaceship::ConnectAPI::Platform::IOS) ||
            app&.get_live_app_store_version(platform: Spaceship::ConnectAPI::Platform::IOS)
  if version.nil?
    UI.important("Could not read the App Store localizations; skipping the release notes coverage check.")
    return
  end

  missing = version.get_app_store_version_localizations.map(&:locale) - release_notes.keys
  unless missing.empty?
    UI.user_error!("App Store Connect has localizations with no release notes: #{missing.join(', ')}. Add fastlane/metadata/ios/<locale>/release_notes.txt for each, then re-run.")
  end
  UI.success("Release notes ready for #{release_notes.keys.join(', ')}.")
end
