default_platform(:mac)

platform :mac do
  desc "Register App ID + download Developer ID provisioning profile"
  lane :provision do
    bundle_id = ENV.fetch("BUNDLE_ID") { read_bundle_id_from_tauri_conf }
    product_name = ENV.fetch("PRODUCT_NAME") { read_product_from_tauri_conf }
    output_dir = ENV.fetch("OUTPUT_DIR", "src-tauri")

    UI.message("Bundle ID: #{bundle_id}")
    UI.message("Product:   #{product_name}")

    # Auth via App Store Connect API key (returns a hash sigh will pick up).
    api_key = app_store_connect_api_key(
      key_id: ENV.fetch("APPLE_API_KEY_ID"),
      issuer_id: ENV.fetch("APPLE_API_ISSUER_ID"),
      key_filepath: ENV.fetch("APPLE_API_KEY_PATH")
    )

    # ── Register App ID (idempotent) ────────────────────────────
    # produce action requires Apple ID login (not API key); use
    # Spaceship::ConnectAPI directly instead. The api_key returned
    # above already configured Spaceship — just call it.
    Spaceship::ConnectAPI.token = Spaceship::ConnectAPI::Token.from(hash: api_key)

    existing = Spaceship::ConnectAPI::BundleId.find(bundle_id)
    if existing
      UI.message("App ID '#{bundle_id}' already registered — skipping create")
    else
      UI.message("Registering App ID '#{bundle_id}' for macOS…")
      Spaceship::ConnectAPI::BundleId.create(
        name: product_name,
        identifier: bundle_id,
        platform: Spaceship::ConnectAPI::BundleIdPlatform::MAC_OS
      )
    end

    # ── Download Developer ID provisioning profile ──────────────
    # sigh's --filename enforces .mobileprovision; rename afterwards.
    sigh(
      developer_id: true,
      platform: "macos",
      app_identifier: bundle_id,
      output_path: output_dir,
      filename: "embedded.mobileprovision",
      force: true
    )

    # sigh writes paths relative to the directory it was launched from
    # (repo root, since the wrapper script does `cd`). Resolve to absolute
    # so the rename works regardless of Fastlane's internal cwd changes.
    repo_root = File.expand_path("..", __dir__)
    src  = File.join(repo_root, output_dir, "embedded.mobileprovision")
    dest = File.join(repo_root, output_dir, "embedded.provisionprofile")
    FileUtils.mv(src, dest)
    UI.success("Profile written to #{dest}")
  end
end

def read_bundle_id_from_tauri_conf
  conf = File.read("../src-tauri/tauri.conf.json", encoding: "UTF-8")
  conf.match(/"identifier"\s*:\s*"([^"]+)"/)[1]
end

def read_product_from_tauri_conf
  conf = File.read("../src-tauri/tauri.conf.json", encoding: "UTF-8")
  conf.match(/"productName"\s*:\s*"([^"]+)"/)[1]
end
