require 'shellwords'
require 'json'
require_relative '../helpers/pretty_table'
require_relative '../helpers/git'
require_relative '../helpers/github'

module Fastlane
  module Actions
    class SubtreesStatusAction < Action
      def self.run(params)
        pr_number = params[:pr_number]
        actions_performed = params[:actions_performed]

        UI.message("Checking status of all subtrees...")
        subtrees = other_action.subtrees_config.map do |subtree, config|
          other_action.subtree_status(
            subtree: subtree,
            repo: config["repo"],
            branch: config["branch"],
            pr_number: pr_number,
          )
        end

        sync_ok = subtrees.all? { |subtree| subtree[:ok] }
        sync_status = sync_ok ? "✅ up to date".green : "⚠️ out of sync".yellow

        PrettyTable.print(
          title: "Subtrees Status: #{sync_status}",
          data: subtrees,
          columns: [:subtree, :status, :last_updated, :changed_files_count, :pr_url],
        )

        if pr_number
          UI.message("📝 Updating PR ##{pr_number} with sync status...")

          summary = <<~MARKDOWN
          ## Subtree Sync Status: #{sync_status.gsub(/\e\[[0-9;]*m/, '')}

          | Subtree | Changed Files | Status | PR |
          | --- | --- | --- | --- |
          #{subtrees.map { |subtree| "| __#{subtree[:subtree]}__ | #{subtree[:changed_files_count] || 0} | #{subtree[:ok] ? "✅" : "⚠️"} #{subtree[:status].gsub(/\e\[[0-9;]*m/, '')} | #{subtree[:pr_url] || "N/A"} |" }.join("\n")}

          MARKDOWN

          comment_url = Github.post_comment(body: summary, pr_number: pr_number)

          UI.success("✅ Posted sync status to PR: #{comment_url}")
        end

        subtrees
      end

      def self.description
        "Check status of all subtrees and optionally update PR description with sync status"
      end

      def self.authors
        ["Suno"]
      end

      def self.return_value
        "Hash containing subtrees status, root status, and overall up_to_date status"
      end

      def self.details
        "This action extracts the logic from the status lane and provides the ability to update a PR description with a status table. The status table shows the sync status of all subtrees and root changes, with indicators for whether each component is up to date."
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(
            key: :pr_number,
            description: "Optional PR number to update with status table in description",
            type: String,
            optional: true
          ),
          FastlaneCore::ConfigItem.new(
            key: :actions_performed,
            description: "Optional actions performed to update with status table in description",
            type: Array,
            optional: true,
            default_value: []
          ),
        ]
      end

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