module Fastlane
  module Actions
    class ExtractApkAction < Action
      def self.run(params)
        bundletool_binary_path = File.expand_path(params[:bundletool_binary_path])
        artifact_path = params[:artifact_path]
        apk_path = params[:apk_path]

        build_info = other_action.analyze_artifacts(artifact_path: artifact_path)
        case build_info[:artifact_type]
        when "APK"
          return artifact_path
        when "AAB"
          bundle_path = artifact_path
        else
          UI.user_error!("Unsupported artifact type: #{build_info[:artifact_type]}")
        end
        output_dir = File.dirname(apk_path)
        FileUtils.mkdir_p(output_dir)

        # Get signing config
        Tempfile.open("keystore.jks") do |keystore_file|
          signing_config = other_action.playstore_signing_config(keystore_file_path: keystore_file.path)

          Dir.chdir(output_dir) do
            apks_file_name = "universal.apks"
            zip_file_name = "universal.zip"
            universal_apk_file_name = "universal.apk"
            Actions.sh([
              bundletool_binary_path,
              "build-apks",
              "--bundle=#{bundle_path}",
              "--output=#{apks_file_name}",
              "--mode=universal",
              "--ks=#{signing_config["android.injected.signing.store.file"]}",
              "--ks-pass=pass:#{signing_config["android.injected.signing.store.password"]}",
              "--ks-key-alias=#{signing_config["android.injected.signing.key.alias"]}",
              "--key-pass=pass:#{signing_config["android.injected.signing.key.password"]}"
            ].join(" "), log: true)
            Actions.sh("mv #{apks_file_name} #{zip_file_name}", log: true)
            Actions.sh("unzip -j #{zip_file_name} #{universal_apk_file_name}", log: true)
            Actions.sh("mv #{universal_apk_file_name} #{apk_path}", log: true)
            FileUtils.rm_rf(zip_file_name)
          end
        end

        UI.success("Universal APK was created successfully: #{apk_path.cyan}")
        apk_path
      end

      def self.description
        "Creates a universal APK from an app bundle using bundletool"
      end

      def self.details
        "This action uses the bundletool script to generate a universal APK from an Android App Bundle (AAB), " \
        "signed with the provided Play Store signing credentials"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :artifact_path,
            description: "Path to the build artifact",
            optional: true,
            verify_block: proc do |value|
              UI.user_error!("Build artifact path must be valid") unless File.exist?(value)
            end),
          FastlaneCore::ConfigItem.new(key: :apk_path,
            description: "Path to the extracted universal APK file",
            type: String,
            verify_block: proc do |value|
              UI.user_error!("Output path must be valid") unless value.end_with?(".apk")
            end),
          FastlaneCore::ConfigItem.new(key: :bundletool_binary_path,
            description: "Path to the bundletool binary",
            type: String,
            default_value: File.expand_path("tools/bundletool.sh"),
            verify_block: proc do |value|
              UI.user_error!("Bundletool binary path must be valid") unless File.exist?(value)
            end)
        ]
      end

      def self.authors
        ["Suno"]
      end

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

      def self.category
        :building
      end
    end
  end
end
