module Fastlane
  module Actions
    class SubtreePullAction < Action
      def self.run(params)
        subtree = params[:subtree]
        repo_name = params[:repo]
        branch = params[:branch]

        # Build full repo URL from repo name
        repo_url = Github.repo_url(repo: repo_name)

        status = other_action.subtree_status(
          subtree: subtree,
          repo: repo_name,
          branch: branch,
          pr_number: params[:pr_number],
        )

        # Check if working directory is clean
        other_action.ensure_git_status_clean

        actions_performed = []
        if status[:last_merge_sha] == nil
          UI.important("🔄 Setting up new subtree...")
          Actions.sh("git subtree add --prefix #{subtree} #{repo_url} #{branch} ")
          UI.success("✅ Successfully added #{subtree} subtree")
          actions_performed << "✅ Added new '#{subtree}' subtree"
        elsif status[:commits_to_pull].count > 0
          begin
            UI.important("🔄 Pulling latest changes from upstream...")
            Actions.sh("git subtree pull --prefix #{subtree} #{repo_url} #{branch} ")
            UI.success("✅ Successfully pulled changes from upstream")
            actions_performed << "✅ Pulled changes from upstream"
          rescue => ex
            if ex.message.include?("fatal: refusing to merge unrelated histories")
              UI.important("⚠️ Unrelated histories detected. Trying subtree pull with --allow-unrelated-histories...")
              Actions.sh("git subtree pull --prefix #{subtree} #{repo_url} #{branch} --allow-unrelated-histories ")
              UI.success("⚠️ Successfully pulled changes from upstream (with unrelated histories)")
              actions_performed << "⚠️ Pulled changes from upstream (with unrelated histories)"
            else
              raise ex
            end
          end
        else
          UI.success("✅ No changes to pull from upstream")
          actions_performed << "✅ No changes to pull from upstream"
        end

        actions_performed
      end

      def self.description
        "Pull changes from upstream repository into a local subtree"
      end

      def self.authors
        ["Suno"]
      end

      def self.return_value
        "Hash with sync results including success status, subtree, and PR details"
      end

      def self.details
        "Pulls latest changes from upstream using git subtree"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(
            key: :repo,
            description: "Repository name (e.g., 'app-android' - org 'suno-ai' will be added automatically)",
            type: String,
            verify_block: proc do |value|
              UI.user_error!(':repo option cannot be empty') if value.to_s.empty?
            end
          ),
          FastlaneCore::ConfigItem.new(
            key: :branch,
            description: "The remote branch to sync with",
            type: String,
            verify_block: proc do |value|
              UI.user_error!(':branch option cannot be empty') if value.to_s.empty?
            end
          ),
          FastlaneCore::ConfigItem.new(
            key: :subtree,
            description: "Subtree path (e.g., 'android', 'ios')",
            type: String,
            verify_block: proc do |value|
              UI.user_error!(':subtree option cannot be empty') if value.to_s.empty?
            end
          ),
          FastlaneCore::ConfigItem.new(
            key: :pr_number,
            description: "PR number from mobile repo to sync (defaults to GITHUB environment if available)",
            type: String,
            optional: true,
            verify_block: proc do |value|
              UI.user_error!(':pr_number option cannot be empty') if value.to_s.empty?
            end
          ),
        ]
      end

      def self.is_supported?(platform)
        true
      end
    end
  end
end
