require_relative "../helpers/github"
require_relative "../helpers/git"
require_relative "../helpers/app"

module Fastlane
  module Actions
    class BuildArtifactsAction < Action
      def self.run(params)
        build_type = params[:build_type]
        build_flavor = params[:build_flavor]
        build_version = other_action.build_version(build_flavor: params[:build_flavor], pr_number: params[:pr_number])
        build_name = "suno-android-#{build_flavor}-#{build_type}-build-#{build_version[:version_code]}-v#{build_version[:version_name]}"

        Tempfile.open("keystore.jks") do |keystore_file|
          signing_config = if build_type == "release"
            build_task = "bundle"
            other_action.playstore_signing_config(keystore_file_path: keystore_file.path)
          else
            build_task = "assemble"
            {}
          end

          other_action.build_android_app(
            task: build_task,
            flavor: build_flavor,
            build_type: build_type,
            print_command: false,
            properties: {
              "android.injected.version.code" => build_version[:version_code],
              "android.injected.version.name" => build_version[:version_name],
              **signing_config
            }
          )
        end

        output_dir = File.join(params[:output_dir], build_name)
        bundle_path = File.join(output_dir, "#{build_name}.aab")
        apk_path = File.join(output_dir, "#{build_name}.apk")
        FileUtils.mkdir_p(output_dir)

        case build_type
        when "release"
          FileUtils.mv(lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH], bundle_path)
          other_action.extract_apk(artifact_path: bundle_path, apk_path: apk_path)
        when "debug"
          bundle_path = nil
          FileUtils.mv(lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH], apk_path)
        end

        {
          **build_version,
          build_name: build_name,
          build_type: build_type,
          build_flavor: build_flavor,
          output_dir: output_dir,
          bundle_path: bundle_path,
          apk_path: apk_path
        }
      end

      def self.description
        "Runs a Gradle release build of the app"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :build_type,
            description: "The build type (#{BuildType::ALL.join(", ")})",
            default_value: "release",
            verify_block: proc do |value|
              UI.user_error!("Invalid build type (must be #{BuildType::ALL.join(", ")})") unless BuildType::ALL.include?(value)
            end),
          FastlaneCore::ConfigItem.new(key: :build_flavor,
            description: "The build flavor (#{BuildFlavor::ALL.join(", ")})",
            default_value: "prod",
            verify_block: proc do |value|
              UI.user_error!("Invalid flavor (must be #{BuildFlavor::ALL.join(", ")})") unless BuildFlavor::ALL.include?(value)
            end),
          FastlaneCore::ConfigItem.new(key: :output_dir,
            description: "The output directory",
            type: String,
            default_value: File.expand_path("build/artifacts"),
            verify_block: proc do |value|
              UI.user_error!("Output directory must be valid") unless !File.exist?(value) || File.directory?(value)
            end),
          FastlaneCore::ConfigItem.new(key: :pr_number,
            description: "Pull request number that triggered the distribution",
            optional: true,
            type: Integer,
            default_value: Github.pr_number,
            verify_block: proc do |value|
              UI.user_error!("Pull request number must be a positive integer") unless value.nil? || value > 0
            end)
        ]
      end

      def self.authors
        ["Suno"]
      end

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