require "base64"
require "fileutils"
require "json"
require "securerandom"
require "tmpdir"

ROOT = File.expand_path("../../..", __dir__)
MOBILE = File.join(ROOT, "apps/mobile")
OUTPUT = File.join(ENV.fetch("RUNNER_TEMP"), "mobile-release")
# Translated "What's new" text keyed by store locale ("appleLocale" or "googleLocale"), sent to Play with each upload
# (500 characters at most). App Store Connect needs the same text when a build is submitted for review.
def release_notes(store)
  JSON.parse(File.read(File.join(MOBILE, "store/metadata.json"))).fetch("localizations").values
    .to_h { |localization| [localization.fetch(store), localization.fetch("releaseNotes").strip] }
end

def secret_file(directory, name, value, base64: false)
  path = File.join(directory, name)
  File.write(path, base64 ? Base64.strict_decode64(value.gsub(/\s/, "")) : value, mode: "wb", perm: 0600)
  path
end

def asc_api_key
  app_store_connect_api_key(
    key_id: ENV.fetch("ASC_KEY_ID"), issuer_id: ENV.fetch("ASC_ISSUER_ID"), key_content: ENV.fetch("ASC_PRIVATE_KEY")
  )
end

# Every Play track (internal, testing, production and custom), read in one aborted edit.
def play_tracks
  require "supply"
  require "supply/options"
  Supply.config = FastlaneCore::Configuration.create(
    Supply::Options.available_options,
    package_name: "me.rxresu", json_key_data: ENV.fetch("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON")
  )
  client = Supply::Client.make_from_config
  client.begin_edit(package_name: "me.rxresu")
  begin
    client.tracks
  ensure
    client.abort_current_edit
  end
end

def play_version_codes
  play_tracks.flat_map { |track| Array(track.releases).flat_map { |release| Array(release.version_codes) } }
end

def whole_number(value)
  Integer(value.to_s, 10)
rescue ArgumentError
  UI.user_error!("Store returned a build number that is not a whole number")
end

desc "Write the latest TestFlight build number and the highest Play version code to GITHUB_OUTPUT"
lane :store_build_numbers do |options|
  version = options.fetch(:version)
  # The upload must exceed both this version's latest build and the latest build of any version.
  ios = [{ version: version }, {}].map do |filter|
    whole_number(latest_testflight_build_number(api_key: asc_api_key, app_identifier: "me.rxresu",
      initial_build_number: 0, **filter))
  end.max
  android = play_version_codes.map { |code| whole_number(code) }.max || 0
  File.write(ENV.fetch("GITHUB_OUTPUT"), "ios=#{ios}\nandroid=#{android}\n", mode: "a")
  UI.message("Latest store build numbers: TestFlight #{ios}, Google Play #{android}")
end

platform :android do
  desc "Write the newest production release users can install (full or staged rollout) to GITHUB_OUTPUT"
  lane :production_release do
    releases = Array(play_tracks.find { |track| track.track == "production" }&.releases)
      .select { |release| %w[completed inProgress].include?(release.status) }
    # Play names a release after its versionName unless someone renames it.
    code, name = releases.map { |release| [Array(release.version_codes).map { |c| whole_number(c) }.max, release.name] }
      .select(&:first).max_by(&:first)
    if code
      File.write(ENV.fetch("GITHUB_OUTPUT"), "version_code=#{code}\nversion_name=#{name.to_s.gsub(/\s+/, ' ').strip}\n", mode: "a")
    end
    UI.message(code ? "Production release: #{name} (#{code})" : "No production release users can install")
  end

  desc "Download the universal APK Play generated and signed for a version code"
  lane :universal_apk do |options|
    download_universal_apk_from_google_play(
      package_name: "me.rxresu", json_key_data: ENV.fetch("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON"),
      version_code: whole_number(options.fetch(:version_code)),
      destination: File.join(OUTPUT, "ReactiveResume.apk")
    )
  end

  desc "Build a signed App Bundle"
  lane :build do
    FileUtils.mkdir_p(OUTPUT)
    Dir.mktmpdir("android-signing-", ENV.fetch("RUNNER_TEMP")) do |directory|
      keystore = secret_file(directory, "upload.jks", ENV.fetch("ANDROID_KEYSTORE_BASE64"), base64: true)
      gradle(
        project_dir: File.join(MOBILE, "android"),
        task: "bundle", build_type: "Release", flags: "--no-daemon",
        print_command: false,
        properties: {
          "android.enableMinifyInReleaseBuilds" => "true",
          "android.enableShrinkResourcesInReleaseBuilds" => "true",
          "android.injected.signing.store.file" => keystore,
          "android.injected.signing.store.password" => ENV.fetch("ANDROID_KEYSTORE_PASSWORD"),
          "android.injected.signing.key.alias" => ENV.fetch("ANDROID_KEY_ALIAS"),
          "android.injected.signing.key.password" => ENV.fetch("ANDROID_KEY_PASSWORD")
        }
      )
      FileUtils.cp(lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH], File.join(OUTPUT, "ReactiveResume.aab"))
      maps = File.join(MOBILE, "android/app/build/generated/sourcemaps/react/release")
      FileUtils.cp_r(maps, File.join(OUTPUT, "sourcemaps")) if Dir.exist?(maps)
      %w[mapping native-debug-symbols].each do |kind|
        source = File.join(MOBILE, "android/app/build/outputs", kind, "release")
        FileUtils.cp_r(source, File.join(OUTPUT, kind)) if Dir.exist?(source)
      end
    end
  end

  desc "Publish to Google Play Internal testing"
  lane :upload do
    # supply reads release notes only from a metadata tree; listing text, images and screenshots stay skipped.
    Dir.mktmpdir("play-metadata-", ENV.fetch("RUNNER_TEMP")) do |metadata|
      release_notes("googleLocale").each do |locale, notes|
        changelogs = File.join(metadata, locale, "changelogs")
        FileUtils.mkdir_p(changelogs)
        File.write(File.join(changelogs, "default.txt"), notes)
      end
      upload_to_play_store(
        package_name: "me.rxresu",
        json_key_data: ENV.fetch("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON"),
        aab: File.join(OUTPUT, "ReactiveResume.aab"),
        track: "internal", release_status: "completed",
        changes_not_sent_for_review: false, rescue_changes_not_sent_for_review: false,
        metadata_path: metadata,
        skip_upload_apk: true, skip_upload_metadata: true, skip_upload_changelogs: false,
        skip_upload_images: true, skip_upload_screenshots: true
      )
    end
  end
end

platform :ios do
  desc "Archive and export a signed production IPA with existing Apple capabilities"
  lane :build do
    FileUtils.mkdir_p(OUTPUT)
    keychain = "mobile-#{ENV.fetch('GITHUB_RUN_ID')}-#{ENV.fetch('GITHUB_RUN_ATTEMPT')}"
    keychain_password = SecureRandom.hex(32)
    create_keychain(name: keychain, password: keychain_password, default_keychain: false, unlock: true, timeout: 0)
    begin
      Dir.mktmpdir("ios-signing-", ENV.fetch("RUNNER_TEMP")) do |directory|
        certificate = secret_file(directory, "distribution.p12", ENV.fetch("IOS_DISTRIBUTION_P12_BASE64"), base64: true)
        import_certificate(
          certificate_path: certificate, certificate_password: ENV.fetch("IOS_DISTRIBUTION_P12_PASSWORD"),
          keychain_name: keychain, keychain_password: keychain_password
        )
        installed = []
        profiles = {}
        begin
          {
            "me.rxresu" => ["ReactiveResume", "IOS_PROVISION_PROFILE_BASE64"],
            "me.rxresu.expo-sharing-extension" => ["expo-sharing-extension", "IOS_SHARE_PROVISION_PROFILE_BASE64"]
          }.each do |bundle_id, (target, secret)|
            profile = secret_file(directory, "#{target}.mobileprovision", ENV.fetch(secret), base64: true)
            data = FastlaneCore::ProvisioningProfile.parse(profile)
            entitlements = data.fetch("Entitlements")
            UI.user_error!("Provisioning profile must belong to #{bundle_id} and team 654ASRW868") unless
              entitlements["application-identifier"] == "654ASRW868.#{bundle_id}" &&
              data.fetch("TeamIdentifier").include?("654ASRW868")
            UI.user_error!("Use an unexpired App Store distribution profile for #{bundle_id}") if
              data["ProvisionedDevices"] || data["ProvisionsAllDevices"] || entitlements["get-task-allow"] ||
              !data["ExpirationDate"] || data["ExpirationDate"].to_time <= Time.now
            UI.user_error!("Provisioning profile for #{bundle_id} must include group.me.rxresu") unless
              entitlements.fetch("com.apple.security.application-groups", []).include?("group.me.rxresu")
            installed << install_provisioning_profile(path: profile)
            profiles[bundle_id] = data.fetch("UUID")
            update_code_signing_settings(
              path: File.join(MOBILE, "ios/ReactiveResume.xcodeproj"),
              use_automatic_signing: false, team_id: "654ASRW868", targets: [target],
              build_configurations: ["Release"], code_sign_identity: "Apple Distribution",
              profile_uuid: data.fetch("UUID")
            )
          end
          cocoapods(podfile: File.join(MOBILE, "ios/Podfile"))
          ENV["SOURCEMAP_FILE"] = File.join(OUTPUT, "main.jsbundle.map")
          build_app(
            workspace: File.join(MOBILE, "ios/ReactiveResume.xcworkspace"), scheme: "ReactiveResume",
            configuration: "Release", export_method: "app-store",
            output_directory: OUTPUT, output_name: "ReactiveResume.ipa",
            archive_path: File.join(ENV.fetch("RUNNER_TEMP"), "ReactiveResume.xcarchive"),
            buildlog_path: File.join(ENV.fetch("RUNNER_TEMP"), "mobile-build-logs"), xcodebuild_formatter: "",
            export_options: {
              signingStyle: "manual", teamID: "654ASRW868",
              provisioningProfiles: profiles
            }
          )
          symbols = File.join(ENV.fetch("RUNNER_TEMP"), "ReactiveResume.xcarchive/dSYMs")
          FileUtils.cp_r(symbols, File.join(OUTPUT, "dSYMs")) if Dir.exist?(symbols)
        ensure
          installed.each { |path| FileUtils.rm_f(path) }
        end
      end
    ensure
      delete_keychain(name: keychain)
    end
  end

  desc "Upload to TestFlight; internal testers get it once App Store Connect has processed it"
  lane :upload do
    # Waiting for processing turns a build that App Store Connect rejects into a failed run.
    upload_to_testflight(
      api_key: asc_api_key, app_identifier: "me.rxresu",
      ipa: File.join(OUTPUT, "ReactiveResume.ipa"),
      distribute_external: false, skip_waiting_for_build_processing: false
    )
  end
end
