def resolved_changelog
  changelog = ENV["NEW_CHANGELOG"]
  if changelog.nil?
    UI.user_error!("Environment variable NEW_CHANGELOG is missing.")
  elsif changelog.strip.empty?
    version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]
    build_number = ENV["NEW_BUILD"]
    changelog = "Release #{version_number} (build #{build_number})"
    UI.message("ℹ️ Empty changelog — using default release notes: #{changelog}")
  end
  changelog
end

lane :set_app_details_android do
  build_number = ENV["NEW_BUILD"]
  changelog = ENV["NEW_CHANGELOG"]

  puts "🔧 Setting Android app details for build #{build_number}..."
  puts "📝 Changelog: #{changelog}"

  android_appicon(
    appicon_image_file: 'fastlane/metadata/app_icon.png',
    # appicon_icon_types: [:launcher],
    appicon_path: 'app/res/mipmap',
    generate_rounded: true
  )
  # sleep(2)
  # android_appicon(
  #   appicon_image_file: 'fastlane/metadata/app_icon.png',
  #   appicon_icon_types: [:notification],
  #   appicon_path: 'app/res/drawable',
  #   appicon_filename: 'ic_notification',
  #   generate_rounded: true
  # )
  # sleep(2)
  # android_appicon(
  #   appicon_image_file: 'fastlane/metadata/app_icon.png',
  #   appicon_icon_types: [:splash_port, :splash_land],
  #   appicon_path: 'app/res/drawable',
  #   appicon_filename: 'splash'
  # )

  # Generate the Changelog
  more_msg = "..."
  final_changelog = changelog.length >= 500 ? changelog.slice(0, 500 - more_msg.length) + more_msg : changelog

  written_files = Dir.glob('fastlane/metadata/android/**/changelogs/' + build_number).map do |file_path|
    puts "📄 Writing changelog to: #{file_path}"
    File.write(file_path, final_changelog)
    file_path
  end

  puts "✅ Changelog written to #{written_files.size} file(s)."

  # Create app icons for Android
  # sh("echo 'Creating app icons for Android...'")
  # sh("echo 'TODO: Implement create_app_icons_android'")
  # sh("echo 'App icons for Android created'")
end

lane :publish_android_firebase do
  changelog = resolved_changelog
  build_number = ENV["NEW_BUILD"]
  version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]
  app_identifier = ENV['ANDROID_APP_IDENTIFIER']
  firebase_app_id_android = ENV['FIREBASE_APP_ID_ANDROID']

  if build_number == nil or build_number.strip == ""
    UI.user_error!("Environment variable NEW_BUILD is missing.")
  end
  if version_number == nil or version_number.strip == ""
    UI.user_error!("Environment variable NEW_VERSION is missing.")
  end
  if app_identifier == nil or app_identifier.strip == ""
    UI.user_error!("Environment variable ANDROID_APP_IDENTIFIER is missing.")
  end
  if firebase_app_id_android == nil or firebase_app_id_android.strip == ""
    UI.user_error!("Environment variable FIREBASE_APP_ID_ANDROID is missing.")
  end

  UI.message("🚀 Publishing Android version #{version_number} (build #{build_number}) to Firebase...")

  firebase_app_distribution(
    service_credentials_file: "../firebase-service-account.json",
    android_artifact_type: "APK",
    android_artifact_path: "../build/app/outputs/flutter-apk/app-release.apk",
    app: firebase_app_id_android,
    testers: "robin.janke@doppelt-digital.de",
    release_notes: changelog
  )
end

lane :publish_android do
  if ENV['FIREBASE_APP_ID_ANDROID'] && !ENV['FIREBASE_APP_ID_ANDROID'].strip.empty?
    publish_android_firebase
  else
    UI.message("ℹ️ FIREBASE_APP_ID_ANDROID not set — skipping Firebase App Distribution.")
  end

  changelog = resolved_changelog
  build_number = ENV["NEW_BUILD"]
  version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]
  app_identifier = ENV['ANDROID_APP_IDENTIFIER']
  json_key_file = ENV['PLAY_STORE_CREDENTIALS_PATH']
  upload_android_screenshots = ENV['CREATE_NEW_SCREENSHOTS']

  if json_key_file == nil or json_key_file.strip == ""
    UI.user_error!("Environment variable PLAY_STORE_CREDENTIALS_PATH is missing.")
  end
  if upload_android_screenshots == nil
    UI.user_error!("Environment variable CREATE_NEW_SCREENSHOTS is missing.")
  end

  # If the file google_data_safety.csv exists, upload it
  if !File.exist?("fastlane/metadata/google_data_safety.csv")
    UI.message("⚠️ google_data_safety.csv file not found, skipping Google Data Safety upload.")
  else
    UI.message("📄 google_data_safety.csv file found, uploading Google Data Safety information...")
    upload_google_data_safety(
      csv_file: "fastlane/metadata/google_data_safety.csv",
      package_name: app_identifier,
      json_key: json_key_file
    )
  end

  UI.message("🚀 Publishing Android version #{version_number} (build #{build_number}) to Play Store...")

  UI.message("📱 Uploading Android screenshots: #{upload_android_screenshots}")

  upload_to_play_store(
    json_key: json_key_file,

    version_name: version_number,
    version_code: build_number,

    package_name: app_identifier,
    aab: "../build/app/outputs/bundle/release/app-release.aab",

    track: "internal",
    release_status: "completed",
    # release_status: "draft",

    # track_promote_to: "internal",
    # track_promote_release_status: "inProgress",

    # Only upload the AAB, not the APK
    skip_upload_apk: true,
    skip_upload_aab: false,

    skip_upload_metadata: false,
    skip_upload_changelogs: false,
    metadata_path: "fastlane/metadata",

    skip_upload_images: false,
    skip_upload_screenshots: !upload_android_screenshots,
    sync_image_upload: true
  )
end

lane :store_review_android do
  build_number = ENV["NEW_BUILD"]
  version_number = ENV["NEW_STORE_VERSION"] || ENV["NEW_VERSION"]

  app_identifier = ENV['ANDROID_APP_IDENTIFIER']
  json_key_file = ENV['PLAY_STORE_CREDENTIALS_PATH']

  if json_key_file == nil or json_key_file.strip == ""
    UI.user_error!("Environment variable PLAY_STORE_CREDENTIALS_PATH is missing.")
  end
  if app_identifier == nil or app_identifier.strip == ""
      UI.user_error!("Environment variable ANDROID_APP_IDENTIFIER is missing.")
  end
  if build_number == nil or build_number.strip == ""
      UI.user_error!("Environment variable NEW_BUILD is missing.")
  end
  if version_number == nil or version_number.strip == ""
      UI.user_error!("Environment variable NEW_VERSION is missing.")
  end

  upload_to_play_store(
    json_key: json_key_file,

    version_name: version_number,
    version_code: build_number,

    package_name: app_identifier,

    track: "internal",
    track_promote_to: "production",
    track_promote_release_status: "completed",

    skip_upload_apk: true,
    skip_upload_aab: true,
    skip_upload_metadata: true,
    skip_upload_changelogs: true,
    skip_upload_images: true,
    skip_upload_screenshots: true
  )
end