require 'tempfile'
require 'fileutils'

module Fastlane
  module Actions
    class LintSourceFilesAction < Action
      def self.run(params)
        # Run SwiftLint with appropriate reporter
        UI.header("Running SwiftLint...")
        swiftlint_binary_path = params[:swiftlint_path]
        baseline_path = params[:baseline_path]

        reporter = other_action.is_ci ? 'github-actions-logging' : 'emoji'

        # Add baseline if it exists and we're using it
        if params[:update_baseline]
          UI.message("Updating baseline #{baseline_path} ...")
          begin
            Actions.sh([swiftlint_binary_path, 'lint',
              '--quiet',
              '--write-baseline', Shellwords.escape(baseline_path),
              '--reporter', 'summary',
            ], log: true)
          rescue => e
            # noop
          end
          UI.success("✅ Baseline updated successfully")
        else
          begin
            Actions.sh([swiftlint_binary_path, 'lint',
              '--reporter', other_action.is_ci ? 'github-actions-logging' : 'emoji',
              *(params[:use_baseline] ? ['--baseline', Shellwords.escape(baseline_path)] : []),
              *(params[:target] ? [params[:target]] : []),
            ], log: true)
          rescue => e
            if $?.exitstatus == 0
              UI.success("✅ SwiftLint found no new violations")
            elsif $?.exitstatus == 2
              UI.user_error!("❌ SwiftLint found violations")
            elsif $?.exitstatus == 3
              UI.user_error!("❌ SwiftLint found serious violations")
            else
              UI.user_error!("❌ SwiftLint failed with exit code #{$?.exitstatus}")
            end
          end
        end

      end

      #####################################################
      # @!group Documentation
      #####################################################

      def self.description
        "Runs SwiftLint with context-appropriate reporting (emoji locally, GitHub Actions on CI)"
      end

      def self.details
        [
          "This action runs SwiftLint with the following features:",
          "• Context-appropriate reporting: 'emoji' for local development, 'github-actions-logging' for CI",
          "• Support for SwiftLint baseline to ignore existing violations",
          "• Automatic baseline updates when requested",
          "• Optional target filtering for focused linting",
          "• Proper exit code handling for different violation levels"
        ].join("\n")
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(
            key: :swiftlint_path,
            description: "Path to SwiftLint executable",
            type: String,
            default_value: "scripts/swiftlint"
          ),
          FastlaneCore::ConfigItem.new(
            key: :use_baseline,
            description: "Use SwiftLint baseline to ignore existing violations",
            type: Boolean,
            default_value: true
          ),
          FastlaneCore::ConfigItem.new(
            key: :baseline_path,
            description: "Path to SwiftLint baseline file (JSON format)",
            type: String,
            default_value: ".swiftlint.baseline.json"
          ),
          FastlaneCore::ConfigItem.new(
            key: :update_baseline,
            description: "Update the baseline file with current violations",
            type: Boolean,
            default_value: false
          ),
          FastlaneCore::ConfigItem.new(
            key: :target,
            description: "Specific target or path to lint (optional)",
            type: String,
            optional: true
          ),
        ]
      end

      def self.output
        []
      end

      def self.return_value
        "Returns nothing, but will fail the lane if SwiftLint violations are found"
      end

      def self.authors
        ["Suno"]
      end

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

      def self.category
        :code_style
      end
    end
  end
end
