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

begin
  require 'gruff'
rescue LoadError
end

module Fastlane
  module Actions
    class GithubWorkflowRunsAction < Action
      def self.run(params)
        repo_name = params[:repo]
        workflow_name = params[:workflow]
        end_date = Time.parse(params[:end_date])
        start_date = Time.parse(params[:start_date])
        workflow_runs = fetch_workflow_runs(repo: repo_name, workflow: workflow_name, start_date: start_date, end_date: end_date)

        aggregated_stats = {}
        workflow_runs.group_by { |run| run[:created_at].strftime('%Y-%m') }.each do |month, runs|
          durations = runs.map { |r| r[:duration_minutes] }
          aggregated_stats[month] = {
            avg_duration: (durations.sum / durations.count).round(2),
            run_count: runs.count,
            min_duration: durations.min,
            max_duration: durations.max
          }
        end
        durations = workflow_runs.map { |r| r[:duration_minutes] }

        UI.header("Workflow Performance Summary")
        UI.message("Total successful runs: #{workflow_runs.count}")
        UI.message("Average duration: #{(durations.sum / durations.count).round(2)} minutes")
        UI.message("Minimum duration: #{durations.min} minutes")
        UI.message("Maximum duration: #{durations.max} minutes")

        {
          runs: workflow_runs,
          stats: aggregated_stats,
          start_date: start_date,
          end_date: end_date,
        }
      end

      private

      def self.fetch_workflow_runs(repo:, workflow:, start_date:, end_date:)
        UI.important("Fetching runs for workflow: #{repo}/#{workflow}")

        all_runs = []
        until_date = end_date
        page_size = 20

        loop do
          runs = JSON.parse(`gh --repo #{Github.org}/#{repo} run list --workflow #{workflow} --status completed --json number,createdAt,updatedAt --created '#{start_date.iso8601}..#{until_date.iso8601}' --limit #{page_size} 2>&1`)
          UI.message("Fetched #{runs.count} runs")
          break if runs.empty?
          until_date = Time.parse(runs.last['createdAt'])
          all_runs = all_runs.concat(runs.map do |run|
            created_at = Time.parse(run['createdAt'])
            updated_at = Time.parse(run['updatedAt'])
            {
              number: run['number'],
              created_at: created_at,
              duration_minutes: ((updated_at - created_at) / 60).round(2),
            }
          end)
          break if runs.length < page_size
        end
        all_runs
      end

      def self.description
        "Generate performance graphs for GitHub Actions workflows over the last 6 months"
      end

      def self.return_value
        "Hash containing workflow performance data and graph data"
      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')",
            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: :output_file,
            description: "Output file path for the performance graph (PNG format)",
            type: String,
            optional: true
          ),
          FastlaneCore::ConfigItem.new(
            key: :start_date,
            description: "Start date for workflow analysis (defaults to 6 months ago)",
            type: String,
            default_value: (Time.now - (6 * 30 * 24 * 60 * 60)).to_s
          ),
          FastlaneCore::ConfigItem.new(
            key: :end_date,
            description: "End date for workflow analysis (defaults to now)",
            type: String,
            default_value: Time.now.to_s
          )
        ]
      end

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