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

module Fastlane
  module Actions
    class DownloadArtifactsAction < Action
      def self.run(params)
        workflow_path = params[:workflow_path]
        workflow_branch = params[:workflow_branch]
        download_dir = File.expand_path(params[:download_dir])
        extension = params[:extension]
        run_id = params[:run_id]
        unless run_id
          run_id = Github::Workflows.get_runs(
            workflow_name: workflow_path,
            branch: workflow_branch,
            limit: 1,
            status: "success"
          )&.first&.[](:databaseId)

          unless run_id
            UI.user_error!("No successful runs found for workflow '#{workflow_path}' on branch '#{workflow_branch}'!")
          end
        end

        workflow_name = Github::Workflows.get_name_from_path(workflow_path)
        run_download_dir = File.join(download_dir, "#{workflow_name}-#{workflow_branch.tr("/", "-")}-#{run_id}")
        FileUtils.rm_rf(run_download_dir)
        FileUtils.mkdir_p(run_download_dir)

        result = Github::Workflows.download_artifacts(
          run_id: run_id,
          download_dir: run_download_dir
        ).find { |file| extension.nil? || file.end_with?(".#{extension}") }

        unless result
          UI.user_error!("No artifact found with extension '.#{extension}' in run #{run_id}")
        end

        result
      end

      def self.description
        "Downloads the most recent successful build artifact for a workflow"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :workflow_path,
            description: "Path to the Github Actions workflow file",
            default_value: ".github/workflows/build-staff.yml",
            verify_block: proc do |value|
              UI.user_error!("Workflow path must be a valid Github Actions workflow: #{value}") unless Github::Workflows.is_valid_path?(value)
            end),
          FastlaneCore::ConfigItem.new(key: :workflow_branch,
            description: "Branch to look for successful workflow runs",
            default_value: Git.default_branch,
            verify_block: proc do |value|
              UI.user_error!("Workflow branch is required") if value.nil? || value.empty?
            end),
          FastlaneCore::ConfigItem.new(key: :download_dir,
            description: "Directory where artifacts will be downloaded",
            default_value: File.expand_path("build/artifacts"),
            verify_block: proc do |value|
              UI.user_error!("Download directory cannot be empty") if value.nil? || value.empty?
              expanded = File.expand_path(value)
              if File.exist?(expanded) && !File.directory?(expanded)
                UI.user_error!("Download directory must be a directory")
              end
              FileUtils.mkdir_p(expanded)
            end),
          FastlaneCore::ConfigItem.new(key: :run_id,
            description: "ID of the run to download artifacts from",
            optional: true,
            verify_block: proc do |value|
              UI.user_error!("Run ID is required") if value.empty?
            end),
          FastlaneCore::ConfigItem.new(key: :extension,
            description: "Extension of the artifact to download",
            optional: true,
            verify_block: proc do |value|
              UI.user_error!("Extension is required") if value.empty?
            end)
        ]
      end

      def self.authors
        ["Suno"]
      end

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