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

module Fastlane
  module Actions
    class PullLokaliseAction < Action
      def self.run(params)
        api_token = params[:api_token]
        project_id = params[:project_id]
        translations_path = params[:translations_path]
        file_format = params[:file_format]
        additional_params = params[:additional_params]

        UI.message("Pulling translations from Lokalise to #{translations_path}")

        # Pull translations using lokalise2 CLI
        lokalise_cmd = "lokalise2 --token #{api_token} file download --project-id #{project_id} --format #{file_format} --original-filenames=true --directory-prefix ''"
        if additional_params
          lokalise_cmd += " #{additional_params}"
        end

        Actions.sh(lokalise_cmd, log: true)

        # Check if there are changes
        git_status = Actions.sh("git status --porcelain #{translations_path}", log: false).strip

        if git_status.empty?
          UI.message("No translation changes downloaded")
        else
          UI.success("✅ Successfully downloaded translations from Lokalise")
          UI.message("Changed files:")
          git_status.split("\n").each do |line|
            UI.message("  #{line}")
          end
        end

        {
          translations_path: translations_path,
          has_changes: !git_status.empty?
        }
      end

      def self.description
        "Pull translations from Lokalise to local files"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(
            key: :api_token,
            env_name: "LOKALISE_API_TOKEN",
            description: "Lokalise API token",
            type: String,
            sensitive: true
          ),
          FastlaneCore::ConfigItem.new(
            key: :project_id,
            description: "Lokalise project ID",
            type: String
          ),
          FastlaneCore::ConfigItem.new(
            key: :translations_path,
            description: "Path where translations should be downloaded",
            type: String,
            default_value: "common-res/src/main/res"
          ),
          FastlaneCore::ConfigItem.new(
            key: :file_format,
            description: "File format for translations",
            type: String,
            default_value: "xml"
          ),
          FastlaneCore::ConfigItem.new(
            key: :base_lang,
            description: "Base language code",
            type: String,
            default_value: "en"
          ),
          FastlaneCore::ConfigItem.new(
            key: :additional_params,
            description: "Additional parameters for lokalise CLI",
            type: String,
            optional: true
          )
        ]
      end

      def self.authors
        ["Suno"]
      end

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