require 'json'
require 'time'
require 'fileutils'
require_relative '../helpers/git'

begin
  require 'gruff'
rescue LoadError
end

module Fastlane
  module Actions
    class GithubWorkflowAnalyticsAction < Action
      def self.run(params)
        workflows = params[:workflow].split(',')

        datasets = workflows.map do |workflow|
          runs = github_workflow_runs(
            repo: params[:repo],
            workflow: workflow,
            start_date: params[:start_date],
            end_date: params[:end_date]
          )

          id = "#{params[:repo]}/#{workflow}"
          labels = runs[:stats].sort_by { |month, _| month }.map { |month, _| month }
          values = labels.map { |month| runs[:stats][month][:avg_duration].round(1) }
          {
            id: id,
            labels: labels,
            values: values,
            start_date: runs[:start_date],
            end_date: runs[:end_date],
          }
        end

        if datasets.empty?
          UI.user_error!("No data found for the specified workflow(s)")
        end

        start_date = datasets.first[:start_date]
        end_date = datasets.first[:end_date]

        # Create line chart
        g = Gruff::Line.new(800)
        g.title = "CI: Average Workflow Runtime in Minutes (#{start_date.strftime('%Y-%m-%d')} - #{end_date.strftime('%Y-%m-%d')})"
        g.title_font_size = 18
        g.legend_at_bottom = true

        # Set data
        datasets.each do |dataset|
          g.data(dataset[:id], dataset[:values])
          g.labels = dataset[:labels]
        end

        # Styling
        g.colors = ['#007AFF']  # iOS blue
        g.theme = {
          colors: ['#007AFF', '#34C759', '#FF9500', '#FF3B30'],
          marker_color: '#E5E5E7',
          font_color: '#1D1D1F',
          background_colors: ['#FFFFFF', '#F2F2F7']
        }

        # Configure appearance
        g.line_width = 3
        g.dot_radius = 4
        g.hide_dots = false
        g.minimum_value = datasets.map { |dataset| dataset[:values].min }.min
        g.maximum_value = datasets.map { |dataset| dataset[:values].max }.max

        # Add grid
        g.marker_font_size = 12
        g.legend_font_size = 14

        # Write to file
        output_file = params[:output_file] || "#{Git.root}/build/graphs/#{params[:repo]}-#{params[:workflow].gsub('[^a-zA-Z0-9]', '_')}-runtime.png"
        FileUtils.mkdir_p(File.dirname(output_file))
        g.write(output_file)

        UI.success("Runtime graph saved to #{output_file}")

        output_file
      end

      def self.description
        "Generate workflow performance analytics graph from GitHub Actions workflow runs"
      end

      def self.return_value
        "Path to the generated PNG graph file"
      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: :workflow,
            description: "GitHub Actions workflow name (e.g., 'ci.yml') or comma-separated list of workflows",
            type: String,
            verify_block: proc do |value|
              UI.user_error!(':workflow option cannot be empty') if value.to_s.empty?
            end
          ),
          FastlaneCore::ConfigItem.new(
            key: :start_date,
            description: "Start date for workflow analysis",
            type: String,
            verify_block: proc do |value|
              UI.user_error!(':start_date option cannot be empty') if value.to_s.empty?
            end
          ),
          FastlaneCore::ConfigItem.new(
            key: :end_date,
            description: "End date for workflow analysis",
            type: String,
            verify_block: proc do |value|
              UI.user_error!(':end_date option cannot be empty') if value.to_s.empty?
            end
          ),
          FastlaneCore::ConfigItem.new(
            key: :output_file,
            description: "Output file path for the performance graph (PNG format)",
            type: String,
            optional: true
          )
        ]
      end

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