default_platform(:ios)

platform :ios do

  # ─── Хелпер: читает MARKETING_VERSION из pbxproj ───
  def current_marketing_version
    pbxproj = File.read("../Rosetta.xcodeproj/project.pbxproj")
    pbxproj.match(/MARKETING_VERSION = ([\d.]+);/)[1]
  end

  # ─── Хелпер: читает CURRENT_PROJECT_VERSION из pbxproj ───
  def current_build_number
    pbxproj = File.read("../Rosetta.xcodeproj/project.pbxproj")
    pbxproj.match(/CURRENT_PROJECT_VERSION = (\d+);/)[1].to_i
  end

  # ─── Хелпер: инкремент patch версии (1.0.4 → 1.0.5) ───
  def bump_patch(version)
    parts = version.split(".").map(&:to_i)
    parts[2] = (parts[2] || 0) + 1
    parts.join(".")
  end

  # ─── Хелпер: обновляет MARKETING_VERSION в pbxproj ───
  def set_marketing_version(new_version)
    path = "../Rosetta.xcodeproj/project.pbxproj"
    content = File.read(path)
    content.gsub!(/MARKETING_VERSION = [\d.]+;/, "MARKETING_VERSION = #{new_version};")
    File.write(path, content)
    UI.success("MARKETING_VERSION → #{new_version}")
  end

  # ─── Хелпер: обновляет CURRENT_PROJECT_VERSION в pbxproj ───
  def set_build_number(new_build)
    path = "../Rosetta.xcodeproj/project.pbxproj"
    content = File.read(path)
    content.gsub!(/CURRENT_PROJECT_VERSION = \d+;/, "CURRENT_PROJECT_VERSION = #{new_build};")
    File.write(path, content)
    UI.success("CURRENT_PROJECT_VERSION → #{new_build}")
  end

  # ─── Автоинкремент build number ───
  desc "Increment build number (CURRENT_PROJECT_VERSION)"
  lane :bump_build do
    new_build = current_build_number + 1
    set_build_number(new_build)
  end

  # ─── Инкремент версии (patch) ───
  desc "Increment version number (patch)"
  lane :bump_version do
    new_version = bump_patch(current_marketing_version)
    set_marketing_version(new_version)
  end

  # ─── Билд для TestFlight ───
  desc "Build and upload to TestFlight"
  lane :beta do
    build_app(
      project: "Rosetta.xcodeproj",
      scheme: "Rosetta",
      configuration: "Release",
      export_method: "app-store",
      clean: true,
      xcargs: "SWIFT_OPTIMIZATION_LEVEL='-Onone'"
    )

    upload_to_testflight(
      skip_waiting_for_build_processing: true
    )

    # Инкремент только после успешной сборки И загрузки
    new_version = bump_patch(current_marketing_version)
    set_marketing_version(new_version)

    new_build = current_build_number + 1
    set_build_number(new_build)
  end

  # ─── Release в App Store ───
  desc "Build and upload to App Store"
  lane :release do
    build_app(
      project: "Rosetta.xcodeproj",
      scheme: "Rosetta",
      configuration: "Release",
      export_method: "app-store",
      clean: true,
      xcargs: "SWIFT_OPTIMIZATION_LEVEL='-Onone'"
    )

    upload_to_app_store(
      force: true,
      skip_screenshots: true
    )

    new_version = bump_patch(current_marketing_version)
    set_marketing_version(new_version)

    new_build = current_build_number + 1
    set_build_number(new_build)
  end

end
