require_relative "../helpers/app"

module Fastlane
  module Actions
    class InstallArtifactAction < Action
      def self.run(params)
        adb_path = params[:adb_path]
        apk_path = params[:apk_path]

        if other_action.is_ci
          UI.user_error!("CI execution is not supported")
        end

        unless are_any_devices_connected(adb_path: adb_path)
          UI.user_error!("No devices connected!")
        end

        build_info = other_action.analyze_artifacts(artifact_path: apk_path)

        UI.message("Installing APK...")
        Actions.sh("#{adb_path} install -r \"#{apk_path}\" 2>&1", log: true)
        UI.success("Successfully installed APK")
        Actions.sh("#{adb_path} shell monkey -p #{build_info[:package_name]} -c android.intent.category.LAUNCHER 1", log: true)
      end

      def self.are_any_devices_connected(adb_path:)
        if other_action.is_ci
          return false
        end
        # Typical output of `./tools/adb.sh devices`:
        #
        # List of devices attached
        # R5CY328LW3W	device
        `#{adb_path} devices`.strip.split("\n").count > 1
      end

      def self.description
        "Installs an APK or AAB artifact on a connected device"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :apk_path,
            description: "The path to the APK file",
            verify_block: proc do |value|
              UI.user_error!("APK path is required") unless File.exist?(value)
            end),
          FastlaneCore::ConfigItem.new(key: :adb_path,
            description: "Path to the adb binary",
            type: String,
            default_value: File.expand_path("tools/adb.sh"),
            verify_block: proc do |value|
              UI.user_error!("ADB binary path must be valid") unless File.exist?(value)
            end)
        ]
      end

      def self.authors
        ["Suno"]
      end

      def self.is_supported?(platform)
        platform == :android
      end
    end
  end
end
