#
#  Fastfile
#  fastlane-ci
#
#  Created by Thibaut Schmitt on 17/11/2026.
#
#  The shared CI lanes of the Openium iOS projects, the fastlane port of the Jenkins shared library openiumpipeline
#  (iOSpipeline, macosStages and the ios-*.sh scripts of devtools). A project imports this file from its own Fastfile:
#
#      import_from_git(url: "ssh://git@gitea.openium.fr:42306/devtools/fastlane-ci.git", branch: "v0.1")
#
#  and sets its CI_* settings in fastlane/.env.default, as the Jenkinsfile set its env.* values, or in one
#  fastlane/.env.<name> per thing it tests, loaded with `fastlane <lane> --env <name>` (see README.md).
#
#  The file is parsed into the Fastfile of the project: its methods (ci_root, xcodebuild_build, with_ci_simulator, …)
#  can be called from the lanes of the project. fastlane already loads the Ruby libraries used below.
#

require "net/http"

default_platform :ios

# -- SETTINGS ---------------------------------------------------------------- #

# run_tests (scan) reads the build settings of the scheme (xcodebuild -showBuildSettings) before every build and test,
# to detect the platform, and gives it 3 seconds, then 6, 12 and 24. On a runner busy with other jobs, loading a project
# and its package graph takes longer, and the lane failed before building. 30 seconds, then 60 and 120: on a quiet
# machine the command answers in a second or two, so this changes nothing there. A project can set others in its .env.
ENV["FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT"] ||= "30"
ENV["FASTLANE_XCODEBUILD_SETTINGS_RETRIES"] ||= "3"

# The flags every xcodebuild of the CI gets. Nobody can approve a macro or a package plugin on a CI machine: without
# them, a dependency macro or a build plugin such as SwiftLint fails the build asking for that approval.
CI_XCARGS = "-skipMacroValidation -skipPackagePluginValidation"

# The tests run in two steps, as on Jenkins (ios-xcodebuild-build-for-testing.sh, then
# ios-xcodebuild-test-without-building.sh): `build-for-testing` compiles the code and the test bundles and writes an
# .xctestrun file that describes them, then `test-without-building -xctestrun` runs the tests from that file, without
# compiling anything. A build error and a test failure show up as two separate fastlane steps.
#
# The two Jenkins stages differ by platform, so each lane takes its settings from one of these.
JENKINS_IOS = {
  # The Thread Sanitizer of SANITIZE_OPTS (ios-generate-build.properties.sh): a data race fails the run.
  thread_sanitizer: true,
  # The test bundles run in several processes, each on its own clone of the simulator.
  parallel_testing: true,
  # At most 2 clones of the simulator: xcodebuild would pick their number from the cores of the Mac, and on a runner that
  # runs several jobs at once, a clone booted among many others can fail to launch the app. CI_TEST_WORKERS overrides it.
  concurrent_workers: 2,
  # Build: at most 12 compile jobs, 60 seconds to find the destination, stop at the first build error.
  build_xcargs: "#{CI_XCARGS} -jobs 12 -destination-timeout 60 -IDEBuildingContinueBuildingAfterErrors=NO",
  # Test: 60 seconds to find the destination, a test running longer than 90 seconds fails instead of blocking the run,
  # one destination at a time.
  test_xcargs: "-destination-timeout 60 -test-timeouts-enabled YES -default-test-execution-time-allowance 90 " \
               "-disable-concurrent-destination-testing"
}.freeze
JENKINS_MACOS = {
  # macosStages.groovy passes only the CI flags and the coverage: no sanitizer, no parallel testing flag (nil: fastlane
  # leaves -parallel-testing-enabled off the command, so the scheme decides). Forcing parallel testing on would run the
  # test bundles in several processes of the same Mac, which share the files of the app (its database, its defaults).
  thread_sanitizer: false,
  parallel_testing: nil,
  concurrent_workers: nil,
  build_xcargs: CI_XCARGS,
  test_xcargs: nil
}.freeze

# arm64 picks the native Mac among the macOS destinations (Catalyst, Designed for iPad, …), as on Jenkins.
MACOS_DESTINATION = "platform=macOS,arch=arm64"

# The files left out of the coverage: tests, dependencies, build products (the regex of ios-code-coverage.sh).
COVERAGE_IGNORE_REGEX = "(/[^/]*Tests/|/checkouts/|/SourcePackages/|/DerivedData/|/\\.build/)"

# quality_cpd: the top-level folders left out of the copy-paste detection (build products, dependencies, generated code:
# the list of ios-cpd.sh), and the files left out wherever they are (generated R2 code, secrets).
CPD_IGNORED_FOLDERS = %w[build DerivedData docs fastlane Carthage Pods vendor lib resgen TestResults firebase].freeze
CPD_IGNORED_FILES = ["**/R2*.swift", "**/Secrets/**/*.swift", "**/AppSecrets/**/*.swift"].freeze

# quality_cpd: the PMD build of the Jenkins agents (PMD 7 snapshot with the Swift 5.9 support), used when present.
JENKINS_PMD = File.join(Dir.home, "pmd-bin-7.0.0-SNAPSHOT/bin/pmd")

platform :ios do

  # -- BEFORE LANES ---------------------------------------------------------- #

  before_all do
    # No fastlane/README.md generated at each run.
    skip_docs

    # The CI resolves the dependencies from the committed Package.resolved files, as ios-build-dependencies.sh does:
    # without them, each run could pick other versions of the dependencies. A container without SPM dependencies has
    # no Package.resolved and is not checked.
    [test_container, ui_tests_container].compact.uniq.each do |container|
      resolved = package_resolved(container)
      next unless File.exist?(resolved)

      _, status = Open3.capture2e("git", "-C", ci_root, "ls-files", "--error-unmatch", resolved)
      relative = resolved.delete_prefix("#{ci_root}/")
      UI.user_error!("Please commit #{relative}: git add -f #{relative}") unless status.success?
    end
  end

  # -- PUBLIC LANES ---------------------------------------------------------- #

  # Each test lane has a build_for_testing_* lane, so that a workflow shows the build and the tests as two steps:
  #
  #     fastlane build_for_testing_ios
  #     fastlane test_ios skip_build:true
  #
  # The build lane writes the .xctestrun file and the products into the DerivedData of the test lane (.build/ci/<test
  # lane>/), where `skip_build:true` finds them. Without skip_build, the test lane builds first, then tests.

  desc "Builds CI_SCHEME for testing on the iOS simulator: the build step of test_ios"
  lane :build_for_testing_ios do
    with_ci_simulator(:build_for_testing_ios, boot: false) do |udid|
      build_scheme(:test_ios, JENKINS_IOS, destination: "id=#{udid}", xcargs: JENKINS_IOS[:build_xcargs])
    end
  end

  desc "Tests CI_SCHEME on a throwaway iOS simulator, with JUnit and coverage " \
       "(skip_build:true: from the build of build_for_testing_ios)"
  lane :test_ios do |options|
    build_for_testing_ios unless skip_build?(options)
    # Looked up before the simulator is created: without a build, the lane fails right away.
    xctestrun = built_xctestrun(:test_ios)
    with_ci_simulator(:test_ios) do |udid|
      test_built_scheme(:test_ios, xctestrun, "id=#{udid}", JENKINS_IOS)
    end
  end

  # A project runs the macOS lanes by calling them (the macos.yml workflow), as TARGETS_MACOS=1 did on Jenkins.
  desc "Builds CI_SCHEME for testing on macOS: the build step of test_macos"
  lane :build_for_testing_macos do
    build_scheme(:test_macos, JENKINS_MACOS, destination: MACOS_DESTINATION, xcargs: JENKINS_MACOS[:build_xcargs])
  end

  desc "Tests CI_SCHEME on macOS, with JUnit and coverage " \
       "(skip_build:true: from the build of build_for_testing_macos)"
  lane :test_macos do |options|
    build_for_testing_macos unless skip_build?(options)
    test_built_scheme(:test_macos, built_xctestrun(:test_macos), MACOS_DESTINATION, JENKINS_MACOS)
  end

  desc "Builds the UI tests of CI_UI_TESTS_SCHEME (and CI_UI_TESTS_PLAN) for the iOS simulator: the build step of " \
       "ui_tests"
  lane :build_for_testing_ui_tests do
    scheme = ui_tests_scheme
    if scheme
      test_plan = ENV["CI_UI_TESTS_PLAN"].to_s
      with_ci_simulator(:build_for_testing_ui_tests, boot: false) do |udid|
        # The app and its UI test runner, and the .xctestrun file that describes them.
        build_for_testing(
          :ui_tests,
          **ui_tests_container,
          scheme: scheme,
          testplan: test_plan.empty? ? nil : test_plan,
          destination: "id=#{udid}",
          cloned_source_packages_path: cloned_packages_path(ui_tests_container)
        )
      end
    end
  end

  desc "Runs the UI tests of CI_UI_TESTS_SCHEME on a throwaway iOS simulator (when CI_UI_TESTS_SCHEME is set) " \
       "(skip_build:true: from the build of build_for_testing_ui_tests)"
  lane :ui_tests do |options|
    scheme = ui_tests_scheme
    next if scheme.nil?

    build_for_testing_ui_tests unless skip_build?(options)

    out = output_dir(:ui_tests)
    xcresult = File.join(out, "#{scheme}.xcresult")
    # xcodebuild refuses to write a result bundle over the one of a previous run.
    FileUtils.rm_rf(xcresult)
    xctestrun = built_xctestrun(:ui_tests)

    with_ci_simulator(:ui_tests) do |udid|
      destination = "id=#{udid}"

      # Run the UI tests from the .xctestrun file. Jenkins never ran UI tests, so they keep their own settings: no
      # parallel testing (it would clone the simulator), no Jenkins time allowance.
      run_tests(
        # fastlane needs the project and the scheme to start, but leaves them off the xcodebuild command when an
        # .xctestrun file is given.
        **ui_tests_container,
        scheme: scheme,
        xctestrun: xctestrun,
        test_without_building: true,
        only_testing: list_setting("CI_UI_TESTS_ONLY_TESTING"),
        destination: destination,
        result_bundle: true,
        result_bundle_path: xcresult,
        output_directory: out,
        output_types: "junit",
        output_files: "report.junit",
        derived_data_path: derived_data(:ui_tests),
        # No screen recordings and logs of the device after the tests: they make the run much slower.
        collect_test_diagnostics: "never",
        xcargs: "-destination-timeout 60",
        # The destination is the simulator created above: fastlane must not look for another one.
        skip_detect_devices: true
      )
    end
  end

  # -- QUALITY LANES --------------------------------------------------------- #

  # The quality stage of iOSpipeline (Swiftlint, CopyPasteDectector, Coverage). Each check lane writes its reports to
  # fastlane/test_output/quality/ and fails only when it cannot run. quality_status then fails on any finding (a lint
  # violation, a duplication, a coverage that went down): quality.yml runs each check with quality_status in a job of
  # its own, marked continue-on-error, so the job of a failing check is red but the run stays green (see README.md).

  desc "Runs quality_lint, quality_cpd, quality_coverage and quality_status, each one even when another fails"
  lane :quality do
    # A missing tool (no PMD on the runner) must not hide the reports of the other steps: every step runs, then the
    # lane fails with the steps that could not run.
    steps = { quality_lint: -> { quality_lint }, quality_cpd: -> { quality_cpd },
              quality_coverage: -> { quality_coverage }, quality_status: -> { quality_status } }
    failed = steps.filter_map do |name, step|
      step.call
      nil
    rescue StandardError => e
      UI.error("#{name} failed: #{e.message}")
      name
    end
    UI.user_error!("Failed quality steps: #{failed.join(', ')}") unless failed.empty?
  end

  desc "SwiftLint on the project, with its .swiftlint.yml: checkstyle.xml (the report of Jenkins) and swiftlint.html"
  lane :quality_lint do
    UI.user_error!("SwiftLint not found: brew install swiftlint") unless executable?("swiftlint")

    out = output_dir(:quality)
    # SwiftLint exits non-zero on a serious violation: the findings are reported, not enforced (ios-lint.sh). The
    # second run reads the cache of the first one.
    { "checkstyle" => "checkstyle.xml", "html" => "swiftlint.html" }.each do |reporter, file|
      Dir.chdir(ci_root) do
        Open3.capture3("swiftlint", "lint", "--quiet", "--reporter", reporter, "--output", File.join(out, file))
      end
    end
    report = File.join(out, "checkstyle.xml")
    UI.user_error!("SwiftLint wrote no report") unless File.exist?(report)

    issues = REXML::Document.new(File.read(report)).get_elements("//error")
    issues.each do |issue|
      file = issue.parent.attributes["name"].delete_prefix("#{ci_root}/")
      UI.message("#{file}:#{issue.attributes['line']}: #{issue.attributes['severity']}: #{issue.attributes['message']}")
    end
    summary = issues.group_by { |issue| issue.attributes["severity"] }.map { |severity, list| "#{list.count} #{severity}" }
    issues.empty? ? UI.success("SwiftLint: no violation") : UI.important("SwiftLint: #{summary.join(', ')}")
  end

  desc "Copy-paste detection of the Swift code with PMD CPD: cpd.xml (the report of Jenkins) and cpd.txt"
  lane :quality_cpd do
    pmd = [ENV["CI_PMD"], JENKINS_PMD, "pmd"].compact.find { |command| executable?(command) }
    UI.user_error!("PMD not found: brew install pmd, or set CI_PMD") if pmd.nil?

    out = output_dir(:quality)
    folders = Dir.children(ci_root).sort.select do |name|
      File.directory?(File.join(ci_root, name)) && !name.start_with?(".") && !CPD_IGNORED_FOLDERS.include?(name)
    end
    # Ruby globs: `*` stays within a folder, `**/` crosses folders (unlike the `find -path` of ios-cpd.sh).
    patterns = CPD_IGNORED_FILES + list_setting("CI_CPD_EXCLUDES").to_a
    excludes = Dir.chdir(ci_root) do
      list_setting("CI_CPD_EXCLUDES").to_a.each do |pattern|
        UI.important("CI_CPD_EXCLUDES: #{pattern} matches no file") if Dir.glob(pattern).empty?
      end
      patterns.flat_map { |pattern| Dir.glob(pattern) }.uniq.sort
    end
    UI.message("CPD: #{excludes.count} file(s) excluded")
    minimum_tokens = ENV.fetch("CI_CPD_MINIMUM_TOKENS", "100")

    # The options of ios-cpd.sh. Run from the root, so the report gives the paths relative to it.
    xml = Dir.chdir(ci_root) do
      capture!(
        pmd, "cpd", "--language", "swift", "--minimum-tokens", minimum_tokens,
        "--format", "net.sourceforge.pmd.cpd.XMLRenderer", "--skip-duplicate-files", "--encoding", "UTF-8",
        "--no-fail-on-violation",
        *folders.flat_map { |folder| ["-d", folder] },
        *excludes.flat_map { |file| ["--exclude", file] }
      )
    end
    File.write(File.join(out, "cpd.xml"), xml)

    # cpd.txt: one block per duplication, its size and its occurrences, readable in the log and in the artifact.
    duplications = REXML::Document.new(xml).get_elements("//duplication")
    blocks = duplications.map do |duplication|
      places = duplication.get_elements("file").map do |file|
        path = file.attributes["path"].delete_prefix("#{ci_root}/")
        "  #{path}:#{file.attributes['line']}-#{file.attributes['endline']}"
      end
      "#{duplication.attributes['lines']} lines, #{duplication.attributes['tokens']} tokens\n#{places.join("\n")}"
    end
    summary = "CPD: #{duplications.count} duplication(s) of #{minimum_tokens} tokens or more"
    File.write(File.join(out, "cpd.txt"), "#{([summary] + blocks).join("\n\n")}\n")
    blocks.each { |block| UI.message(block) }
    duplications.empty? ? UI.success(summary) : UI.important(summary)
  end

  desc "Line coverage of every test lane, from the coverage.json files in fastlane/test_output: coverage.txt"
  lane :quality_coverage do
    out = output_dir(:quality)
    # The test lanes write fastlane/test_output/<lane>/coverage.json ({ "Target" => ratio }). In a quality job, the
    # workflow downloads the artifacts of the test jobs there.
    reports = Dir.glob(File.join(ci_root, "fastlane/test_output/*/coverage.json")).sort
    rows = reports.flat_map do |report|
      lane = File.basename(File.dirname(report))
      JSON.parse(File.read(report)).map { |target, ratio| [lane, target, ratio * 100] }
    end
    lane_width = rows.map { |row| row[0].length }.max.to_i
    target_width = rows.map { |row| row[1].length }.max.to_i
    lines = rows.map do |lane, target, value|
      format("%-#{lane_width}<lane>s  %-#{target_width}<target>s  %6.2<value>f %%", lane: lane, target: target, value: value)
    end
    lines = ["No coverage report in fastlane/test_output"] if lines.empty?
    File.write(File.join(out, "coverage.txt"), "#{lines.join("\n")}\n")
    lines.each { |line| UI.message("Coverage #{line}") }
  end

  desc "Sets one Gitea commit status per quality report, compared with the default branch, and fails on any finding"
  lane :quality_status do
    # The reports present in fastlane/test_output/quality/ and the coverage.json of the test lanes: in a job that ran
    # one check, only the status of that check.
    statuses = quality_statuses
    token = ENV["GITEA_TOKEN"].to_s
    send = !token.empty? && !ENV["GITHUB_SHA"].to_s.empty?
    # On a developer machine: the statuses are only printed, without a base to compare with.
    UI.important("GITEA_TOKEN or GITHUB_SHA not set: the commit statuses are not sent") unless send

    base = send ? quality_base_statuses(token) : {}
    run_url = "#{ENV['GITHUB_SERVER_URL']}/#{ENV['GITHUB_REPOSITORY']}/actions/runs/#{ENV['GITHUB_RUN_ID']}"
    failures = statuses.filter_map do |status|
      description, state = status[:compare].call(base[status[:context]])
      UI.message("#{status[:context]}: #{description}")
      if send
        gitea_api(token, :post, "statuses/#{ENV['GITHUB_SHA']}",
                  { context: status[:context], description: description, state: state, target_url: run_url })
      end
      "#{status[:context]}: #{description}" if state == "failure"
    end
    UI.user_error!("Quality checks that failed:\n#{failures.join("\n")}") unless failures.empty?
  end

  # -- PRIVATE METHODS ------------------------------------------------------- #

  # The root of the project that imports this file (not of the fastlane-ci clone): the parent of its fastlane folder.
  # fastlane runs the actions from the root but `sh` from fastlane/, so every path is made absolute from it.
  def ci_root
    @ci_root ||= File.expand_path("..", FastlaneCore::FastlaneFolder.path)
  end

  # A required setting: fails the lane with the name of the missing variable.
  def required_setting(name)
    value = ENV[name].to_s
    UI.user_error!("#{name} is not set: add it to fastlane/.env.default, or to the .env.<name> of --env") if value.empty?
    value
  end

  # A comma-separated setting as an array, nil when it is not set.
  def list_setting(name)
    values = ENV[name].to_s.split(",").map(&:strip).reject(&:empty?)
    values.empty? ? nil : values
  end

  # The container of the tested scheme, as run_tests options: { package_path: }, { project: } or { workspace: }, from
  # CI_PACKAGE_PATH, CI_PROJECT or CI_WORKSPACE (relative to the root). Nil when none is set.
  def test_container
    container_from("CI_PACKAGE_PATH", "CI_PROJECT", "CI_WORKSPACE")
  end

  # The container of the UI tests: CI_UI_TESTS_PROJECT or CI_UI_TESTS_WORKSPACE, else the one of the tests.
  def ui_tests_container
    return nil if ENV["CI_UI_TESTS_SCHEME"].to_s.empty?

    container_from(nil, "CI_UI_TESTS_PROJECT", "CI_UI_TESTS_WORKSPACE") || test_container
  end

  def container_from(package_variable, project_variable, workspace_variable)
    { package_path: package_variable, project: project_variable, workspace: workspace_variable }.each do |key, variable|
      value = variable && ENV[variable].to_s
      return { key => File.expand_path(value, ci_root) } unless value.to_s.empty?
    end
    nil
  end

  # The Package.resolved of a container: where Xcode writes it for a package, a project or a workspace.
  def package_resolved(container)
    key, path = container.first
    case key
    when :package_path then File.join(path, "Package.resolved")
    when :project then File.join(path, "project.xcworkspace/xcshareddata/swiftpm/Package.resolved")
    else File.join(path, "xcshareddata/swiftpm/Package.resolved")
    end
  end

  # $HOME/ClonedSourcePackagesDir/<key>: the folder of the SPM checkouts of a container. The key is the sha of its
  # Package.resolved, else the name of the root folder: the cache key of ios-build-dependencies.sh, so Jenkins and
  # Gitea reuse the same checkouts on the same machine, and a change of the pinned versions gets a new folder.
  def cloned_packages_path(container = test_container)
    resolved = package_resolved(container)
    key = File.exist?(resolved) ? Digest::SHA1.file(resolved).hexdigest : File.basename(ci_root)
    File.join(Dir.home, "ClonedSourcePackagesDir", key)
  end

  # The name of a lane run: the lane, followed by the environment given with `--env` when there is one (test_ios-sample
  # for `fastlane test_ios --env sample`). A project that tests several things (a package and an app) gives each one
  # its own fastlane/.env.<name>, so the runs of the same lane never share their folders, reports or simulators.
  def run_name(lane)
    environment = Actions.lane_context[Actions::SharedValues::ENVIRONMENT].to_s.tr(",", "-")
    environment.empty? ? lane.to_s : "#{lane}-#{environment}"
  end

  # fastlane/test_output/<run name>/: the JUnit report, the xcresult and the coverage of a lane. Created when missing.
  def output_dir(lane)
    File.join(ci_root, "fastlane/test_output", run_name(lane)).tap { |dir| FileUtils.mkdir_p(dir) }
  end

  # .build/ci/<run name>/: one DerivedData per lane and environment, so that the jobs running at the same time never
  # build in the same folder.
  def derived_data(lane)
    File.join(ci_root, ".build/ci", run_name(lane))
  end

  # Runs a command without a shell (the arguments are passed as is) and returns its output. Fails the lane with the
  # error output of the command when it fails.
  def capture!(*command)
    stdout, stderr, status = Open3.capture3(*command)
    UI.user_error!("#{command.join(' ')} failed: #{stderr.strip}") unless status.success?
    stdout.strip
  end

  # The identifier of the iOS runtime of the CI simulators: the one of CI_RUNTIME, given by its version (27.0), its name
  # (iOS 27.0) or its identifier (com.apple.CoreSimulator.SimRuntime.iOS-27-0), else the newest one (latest_ios_runtime).
  # A runtime can be restricted to some devices: the iOS 27.1 runtimes create only iPhone Duo simulators, so with
  # Xcode 27.1 the other iPhones need CI_RUNTIME=27.0.
  def ios_runtime
    requested = ENV["CI_RUNTIME"].to_s.strip
    return latest_ios_runtime if requested.empty?

    runtimes = JSON.parse(capture!("xcrun", "simctl", "list", "runtimes", "--json"))["runtimes"]
                   .select { |r| r["isAvailable"] && r["identifier"].include?("SimRuntime.iOS-") }
    runtime = runtimes.find { |r| [r["version"], r["name"], r["identifier"]].include?(requested) }
    if runtime.nil?
      installed = runtimes.map { |r| r["version"] }.uniq.join(", ")
      UI.user_error!("CI_RUNTIME=#{requested}: no such iOS simulator runtime is installed (installed: #{installed})")
    end
    runtime["identifier"]
  end

  # The identifier of the newest installed iOS runtime that the selected Xcode supports, that is, not newer than its
  # iOS simulator SDK. A runtime installed by a newer Xcode on the same machine (iOS 27.1 next to Xcode 27.0) is
  # skipped, so the tests always run on a runtime that matches the SDK they were built with.
  def latest_ios_runtime
    sdk_version = Gem::Version.new(capture!("xcrun", "--sdk", "iphonesimulator", "--show-sdk-version"))
    runtimes = JSON.parse(capture!("xcrun", "simctl", "list", "runtimes", "--json"))["runtimes"]
    runtime = runtimes
              .select { |r| r["isAvailable"] && r["identifier"].include?("SimRuntime.iOS-") }
              .select { |r| Gem::Version.new(r["version"]) <= sdk_version }
              .max_by { |r| Gem::Version.new(r["version"]) }
    UI.user_error!("No iOS simulator runtime up to #{sdk_version} is installed") if runtime.nil?
    runtime["identifier"]
  end

  # A port of ios-simulators-create.sh / -delete.sh. It creates a simulator for this run only, named
  # CI-<root folder>-<run id>-<lane>, of the CI_DEVICE type (iPhone 17 Pro by default), boots it, sets a fixed status bar
  # (9:41, full battery, CI_SIMULATOR_OPERATOR_NAME), then gives its UDID to the block. Each job gets its own
  # simulator, so the jobs running at the same time on the runner never share one. The `ensure` deletes it even when
  # the tests fail or the lane is interrupted.
  #
  # The build_for_testing_* lanes take one with `boot: false`, created and deleted around the build: a build needs a
  # concrete simulator, not a booted one. The generic destination (generic/platform=iOS Simulator) is not enough: its
  # .xctestrun file has no CodeCoverageBuildableInfos, so the tests run without coverage, and the Thread Sanitizer
  # library it injects (DYLD_INSERT_LIBRARIES) does not point to the runtime. The type and the runtime are the same
  # as those of the test simulator, so the .xctestrun file runs on it.
  def with_ci_simulator(lane, boot: true)
    device_type = ENV["CI_DEVICE"] || "iPhone 17 Pro"
    # GITHUB_RUN_ID is set by Gitea Actions. On a developer machine, a random suffix avoids name clashes.
    run_id = ENV["GITHUB_RUN_ID"] || "local-#{SecureRandom.hex(3)}"
    name = "CI-#{File.basename(ci_root)}-#{run_id}-#{run_name(lane)}"
    runtime = ios_runtime
    UI.message("Creating simulator #{name} (#{device_type}, #{runtime})")
    udid = capture!("xcrun", "simctl", "create", name, device_type, runtime)
    begin
      if boot
        capture!("xcrun", "simctl", "boot", udid)
        # Waits until the simulator has finished booting, so that the first test does not time out.
        capture!("xcrun", "simctl", "bootstatus", udid)
        capture!("xcrun", "simctl", "status_bar", udid, "override", "--time", "9:41", "--batteryState", "charged",
                 "--batteryLevel", "100", "--operatorName", ENV["CI_SIMULATOR_OPERATOR_NAME"] || "Openium",
                 "--dataNetwork", "wifi", "--cellularBars", "4")
      end
      yield udid
    ensure
      UI.message("Deleting simulator #{name}")
      # Errors ignored on purpose: the cleanup must not hide the result of the tests.
      Open3.capture3("xcrun", "simctl", "shutdown", udid)
      Open3.capture3("xcrun", "simctl", "delete", udid)
    end
  end

  # Runs `xcodebuild build` with the given arguments and the CI flags, for the lanes of a project. The `cd` is needed
  # because `sh` runs in fastlane/. The output goes through xcbeautify when it is installed (readable logs);
  # `pipefail` keeps the exit code of xcodebuild, not the one of xcbeautify.
  def xcodebuild_build(*arguments)
    command = "cd #{ci_root.shellescape} && #{['xcodebuild', 'build', *arguments, *CI_XCARGS.split].shelljoin}"
    if system("command -v xcbeautify > /dev/null")
      sh("set -o pipefail && #{command} | xcbeautify", log: true)
    else
      sh(command, log: true)
    end
  end

  # `skip_build:true` on the command line (fastlane may give it as a string).
  def skip_build?(options)
    options[:skip_build].to_s == "true"
  end

  # CI_UI_TESTS_SCHEME, or nil (with a message) when the project has no UI tests.
  def ui_tests_scheme
    scheme = ENV["CI_UI_TESTS_SCHEME"].to_s
    if scheme.empty?
      UI.important("CI_UI_TESTS_SCHEME is not set: no UI tests")
      return nil
    end
    if ui_tests_container.nil?
      UI.user_error!("Set CI_UI_TESTS_PROJECT, CI_UI_TESTS_WORKSPACE, CI_PROJECT or CI_WORKSPACE in fastlane/.env.*")
    end
    scheme
  end

  # The container of CI_SCHEME, or a failure naming the settings to add.
  def required_test_container
    container = test_container
    UI.user_error!("Set CI_PACKAGE_PATH, CI_PROJECT or CI_WORKSPACE in fastlane/.env.*") if container.nil?
    container
  end

  # The build step of test_ios and test_macos (Jenkins: ios-xcodebuild-build-for-testing.sh): build-for-testing of
  # CI_SCHEME (and CI_TEST_PLAN when set), with code coverage, into the DerivedData of the lane. `jenkins` is
  # JENKINS_IOS or JENKINS_MACOS; `destination` and `xcargs` are the run_tests options of the build.
  def build_scheme(lane, jenkins, destination:, xcargs:)
    container = required_test_container
    test_plan = ENV["CI_TEST_PLAN"].to_s
    build_for_testing(
      lane,
      **container,
      scheme: required_setting("CI_SCHEME"),
      testplan: test_plan.empty? ? nil : test_plan,
      destination: destination,
      code_coverage: true,
      thread_sanitizer: jenkins[:thread_sanitizer],
      cloned_source_packages_path: cloned_packages_path(container),
      xcargs: xcargs
    )
  end

  # The test step of test_ios and test_macos (Jenkins: ios-xcodebuild-test-without-building.sh): test-without-building
  # from the .xctestrun file of build_scheme (see built_xctestrun), on the destination. It writes report.junit and
  # <scheme>.xcresult in the output folder of the lane. `jenkins` is JENKINS_IOS or JENKINS_MACOS: the sanitizer,
  # parallel testing and flags of the platform. The coverage summary runs in `ensure`, so failed tests still get their
  # coverage, as on Jenkins.
  def test_built_scheme(lane, xctestrun, destination, jenkins)
    scheme = required_setting("CI_SCHEME")
    container = required_test_container

    out = output_dir(lane)
    xcresult = File.join(out, "#{scheme}.xcresult")
    # xcodebuild refuses to write a result bundle over the one of a previous run.
    FileUtils.rm_rf(xcresult)

    begin
      run_tests(
        # The .xctestrun file lists the test bundles to run, with the coverage and sanitizer settings of the build.
        # fastlane still needs the container and the scheme to start, but leaves them off the xcodebuild command
        # when an .xctestrun file is given.
        **container,
        scheme: scheme,
        xctestrun: xctestrun,
        test_without_building: true,
        destination: destination,
        code_coverage: true,
        thread_sanitizer: jenkins[:thread_sanitizer],
        parallel_testing: jenkins[:parallel_testing],
        concurrent_workers: jenkins[:concurrent_workers] && ENV.fetch("CI_TEST_WORKERS", jenkins[:concurrent_workers]).to_i,
        result_bundle: true,
        result_bundle_path: xcresult,
        output_directory: out,
        output_types: "junit",
        output_files: "report.junit",
        # The coverage data (Coverage.profdata) is written to this DerivedData, where the llvm-cov fallback reads it.
        derived_data_path: derived_data(lane),
        xcargs: jenkins[:test_xcargs],
        # The destination is explicit (a simulator UDID or the Mac): fastlane must not look for another device.
        skip_detect_devices: true
      )
    ensure
      coverage_summary(xcresult, derived_data(lane)) if File.exist?(xcresult)
    end
  end

  # Step 1 of a test run: `xcodebuild build-for-testing` with the given run_tests options, into the DerivedData of the
  # lane. Returns the path of the .xctestrun file it writes in Build/Products/
  # (<scheme>_<test plan>_<platform><version>-<arch>.xctestrun, or <scheme>_<platform><version>-<arch>.xctestrun).
  def build_for_testing(lane, xcargs: CI_XCARGS, **options)
    # The .xctestrun files of a previous run (another platform or OS version) stay in Build/Products: they are removed
    # so that the one returned is the one of this build.
    FileUtils.rm_f(Dir.glob(File.join(derived_data(lane), "Build/Products/*.xctestrun")))

    run_tests(
      build_for_testing: true,
      derived_data_path: derived_data(lane),
      xcargs: xcargs,
      skip_detect_devices: true,
      **options
    )

    built_xctestrun(lane)
  end

  # Step 2 of a test run starts from here: the .xctestrun file that build_for_testing wrote in the DerivedData of the
  # lane, possibly in an earlier fastlane run (the build_for_testing_* lanes). Fails when there is none.
  def built_xctestrun(lane)
    products = File.join(derived_data(lane), "Build/Products")
    xctestrun = Dir.glob(File.join(products, "*.xctestrun")).max_by { |path| File.mtime(path) }
    if xctestrun.nil?
      UI.user_error!("No .xctestrun file in #{products}: run the build_for_testing_* lane first, or drop skip_build")
    end
    UI.message("Testing from #{xctestrun}")
    xctestrun
  end

  # A port of ios-code-coverage.sh: prints the line coverage and writes it to coverage.json (machine readable) and
  # coverage.txt (one line per target) next to the xcresult. The targets are the ones of CI_COVERED_TARGETS, else every
  # target xccov reports but the test bundles. Coverage never fails the lane: an error is only printed, as on Jenkins.
  def coverage_summary(xcresult, derived_data)
    targets = list_setting("CI_COVERED_TARGETS")
    coverage = coverage_from_xccov(xcresult, targets) || coverage_from_profdata(derived_data, targets)
    if coverage.nil? || coverage.empty?
      UI.important("No coverage report for #{xcresult}")
      return
    end

    out = File.dirname(xcresult)
    File.write(File.join(out, "coverage.json"), JSON.pretty_generate(coverage))
    width = coverage.keys.map(&:length).max
    lines = coverage.map do |target, line_coverage|
      format("%-#{width}<target>s %6.2<value>f %%", target: target, value: line_coverage * 100)
    end
    File.write(File.join(out, "coverage.txt"), "#{lines.join("\n")}\n")
    lines.each { |line| UI.success("Coverage #{line}") }
  rescue StandardError => e
    UI.important("Coverage summary failed: #{e.message}")
  end

  # The usual source: the coverage report stored in the xcresult, read with xccov. Returns { "Target" => 0.92, … }
  # (ratios between 0 and 1), or nil when xccov can not read it, which happens on package schemes with Xcode 27.
  def coverage_from_xccov(xcresult, targets)
    stdout, stderr, status = Open3.capture3("xcrun", "xccov", "view", "--report", "--json", xcresult)
    unless status.success?
      UI.important("xccov failed on #{xcresult}, falling back to llvm-cov: #{stderr.strip}")
      return nil
    end

    JSON.parse(stdout)["targets"].to_a.each_with_object({}) do |target, coverage|
      # xccov names the targets with their product extension (App.app, Kit.framework, Kit.o, …).
      name = File.basename(target["name"], ".*")
      next if targets ? !targets.include?(name) : name.end_with?("Tests")

      coverage[name] = target["lineCoverage"]
    end
  end

  # The fallback when xccov fails: the raw coverage data that `-enableCodeCoverage` leaves in the DerivedData.
  # llvm-cov reads the newest Coverage.profdata against the instrumented binaries (the test bundles, in which the
  # package code is linked, and the apps) and gives the covered and total lines of every source file. The coverage of a
  # target is the sum over its files under Sources/<target>/; without CI_COVERED_TARGETS, the sum over every file.
  # Same result shape as coverage_from_xccov.
  def coverage_from_profdata(derived_data, targets)
    profdata = Dir.glob(File.join(derived_data, "**/Build/ProfileData/**/Coverage.profdata"))
                  .max_by { |path| File.mtime(path) }
    if profdata.nil?
      UI.important("No Coverage.profdata in #{derived_data}")
      return nil
    end

    # The executable inside each bundle: <name>.xctest/<name> on iOS, <name>.xctest/Contents/MacOS/<name> on macOS.
    binaries = Dir.glob(File.join(derived_data, "**/Build/Products/**/*.{xctest,app}")).filter_map do |bundle|
      name = File.basename(bundle, ".*")
      [File.join(bundle, name), File.join(bundle, "Contents/MacOS", name)].find { |path| File.file?(path) }
    end
    if binaries.empty?
      UI.important("No instrumented binary in #{derived_data}")
      return nil
    end

    # llvm-cov takes the first binary as is and every other one after -object.
    objects = [binaries.first] + binaries.drop(1).flat_map { |binary| ["-object", binary] }
    stdout = capture!("xcrun", "llvm-cov", "export", "-summary-only", "-instr-profile", profdata,
                      "-ignore-filename-regex=#{COVERAGE_IGNORE_REGEX}", *objects)
    files = JSON.parse(stdout)["data"].flat_map { |data| data["files"] }
    groups = targets ? targets.to_h { |name| [name, "/Sources/#{name}/"] } : { "All files" => "" }
    groups.each_with_object({}) do |(name, folder), coverage|
      summaries = files.select { |file| file["filename"].include?(folder) }.map { |file| file["summary"]["lines"] }
      total = summaries.sum { |summary| summary["count"] }
      coverage[name] = summaries.sum { |summary| summary["covered"] }.fdiv(total) if total.positive?
    end
  end

  # The commit statuses of quality_status, from the reports: { context:, description:, compare: }. `compare` takes
  # the description of the same status on the base commit (or nil) and returns the description with the difference,
  # and the state: failure when a lint or CPD finding exists (the quality gates of Jenkins, threshold 1) or when the
  # coverage of a target went down, success otherwise. The descriptions start with the numbers they are compared by.
  def quality_statuses
    out = output_dir(:quality)
    statuses = []
    { "SwiftLint" => ["checkstyle.xml", "//error", "violation(s)"],
      "CPD" => ["cpd.xml", "//duplication", "duplication(s)"] }.each do |name, (file, xpath, unit)|
      report = File.join(out, file)
      next unless File.exist?(report)

      count = REXML::Document.new(File.read(report)).get_elements(xpath).count
      statuses << {
        context: "Quality / #{name}",
        description: "#{count} #{unit}",
        compare: lambda do |base|
          previous = base&.[](/\A(\d+) /, 1)
          difference = previous ? format(" (%+d vs %s)", count - previous.to_i, quality_base_name) : ""
          ["#{count} #{unit}#{difference}", count.zero? ? "success" : "failure"]
        end
      }
    end
    Dir.glob(File.join(ci_root, "fastlane/test_output/*/coverage.json")).sort.each do |report|
      coverage = JSON.parse(File.read(report)).transform_values { |ratio| (ratio * 100).round(2) }
      statuses << {
        context: "Quality / Coverage #{File.basename(File.dirname(report))}",
        description: coverage.map { |target, value| format("%s %.2f%%", target, value) }.join(", "),
        compare: lambda do |base|
          previous = base.to_s.scan(/(\S+) ([\d.]+)%/).to_h.transform_values(&:to_f)
          parts = coverage.map do |target, value|
            difference = previous.key?(target) ? format(" (%+.2f)", value - previous[target]) : ""
            format("%s %.2f%%%s", target, value, difference)
          end
          lower = coverage.any? { |target, value| previous.key?(target) && value < previous[target] }
          suffix = previous.empty? ? "" : " vs #{quality_base_name}"
          ["#{parts.join(', ')}#{suffix}", lower ? "failure" : "success"]
        end
      }
    end
    statuses
  end

  # The name of the base commit in the descriptions, set by quality_base_statuses.
  def quality_base_name
    @quality_base_name ||= "base"
  end

  # The descriptions of the latest statuses of the base commit, by context. The base commit is the previous head of the
  # branch for a push to the default branch (GITHUB_EVENT_PATH), else the head of the default branch. Empty when it has none (its quality job did
  # not run yet), or when the API fails: the statuses are then sent without a difference.
  def quality_base_statuses(token)
    default_branch = gitea_api(token, :get, "")&.fetch("default_branch", nil)
    return {} if default_branch.nil?

    branch = ENV["GITHUB_REF_NAME"].to_s
    if branch == default_branch
      event = ENV["GITHUB_EVENT_PATH"] ? JSON.parse(File.read(ENV["GITHUB_EVENT_PATH"])) : {}
      ref = event["before"].to_s
      return {} if ref.empty? || ref.match?(/\A0+\z/)

      @quality_base_name = ref[0, 8]
    else
      ref = default_branch
      @quality_base_name = default_branch
    end
    # The newest status first: the first one of each context is its latest.
    statuses = gitea_api(token, :get, "commits/#{ref}/statuses?sort=recentupdate&limit=50") || []
    statuses.each_with_object({}) { |status, latest| latest[status["context"]] ||= status["description"] }
  end

  # A call to the API of the repository of the run (/api/v1/repos/<owner>/<repo>/<path>) with the token of the job.
  # Returns the parsed JSON, or nil when the call fails: the statuses never fail the CI.
  def gitea_api(token, method, path, body = nil)
    uri = URI("#{ENV['GITHUB_SERVER_URL']}/api/v1/repos/#{ENV['GITHUB_REPOSITORY']}/#{path}".chomp("/"))
    request = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri)
    request["Authorization"] = "token #{token}"
    request["Content-Type"] = "application/json"
    request.body = JSON.generate(body) if body
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
    unless response.is_a?(Net::HTTPSuccess)
      UI.important("Gitea API #{method.upcase} #{uri.path}: #{response.code} #{response.body.to_s[0, 200]}")
      return nil
    end
    JSON.parse(response.body)
  rescue StandardError => e
    UI.important("Gitea API #{method.upcase} #{path}: #{e.message}")
    nil
  end

  # True when `command` is an executable path, or a command found on the PATH.
  def executable?(command)
    return File.executable?(command) if command.include?("/")

    ENV["PATH"].split(File::PATH_SEPARATOR).any? { |dir| File.executable?(File.join(dir, command)) }
  end
end
