require 'rest-client'
require 'json'
require 'redis'

module HuaweiCloud
  class CodeCheck
    CONFIG = Rails.application.config_for(:configuration)['huawei_code_check']
    PROJECT_ID = CONFIG['product_id']
    REGION = CONFIG['region']

    def initialize
      @region = REGION
      @project_id = PROJECT_ID
      @token = HuaweiCloud::ImaAccount.new.token
      @headers = {
        "Content-Type" => "application/json;charset=utf8",
        "X-Auth-Token" => @token,
        "Host" => "codearts-check.#{@region}.myhuaweicloud.com"
      }
    end


    # 创建检查任务
    # params: git_url, git_branch, languages (array), optional rule_sets etc
    def create_task(git_url:, git_branch:, languages: nil, rule_sets: nil, task_type: "full", endpoint_id: nil, username: nil, access_token: nil, resource_pool_id: nil)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/#{@project_id}/task"
      Rails.logger.info "################### create_task url #{url}"


      body = {
        git_url: git_url,
        git_branch: git_branch,
        task_type:task_type
      }
      body[:language] = languages if languages
      body[:rule_sets] = rule_sets if rule_sets
      body[:endpoint_id] = endpoint_id if endpoint_id
      body[:username] = username if username
      body[:access_token] = access_token if access_token
      body[:resource_pool_id] = resource_pool_id if resource_pool_id
      Rails.logger.info body.to_json
      huawei_request(:post, url, body: body)
    end

    def run_task(task_id,git_branch:)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/tasks/#{task_id}/run"
      body = {
      }
      body[:language] = git_branch if git_branch
      huawei_request(:post, url, body: body)
    end

    def query_task(task_id)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/tasks/#{task_id}/progress"
      huawei_request(:get, url)
    end

    def defects_summary(task_id,query)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/tasks/#{task_id}/defects-summary"
      huawei_request(:get, url, params: query)
    end


    def defects_detail(task_id,query)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/tasks/#{task_id}/defects-detail"
      huawei_request(:get, url, params: query)
    end

    def defects_statistic(task_id)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/tasks/#{task_id}/defects-statistic"
      huawei_request(:get, url)
    end

    def metrics_summary(task_id)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/#{@project_id}/tasks/#{task_id}/metrics-summary"
      huawei_request(:get, url)
    end

    def defect_status(task_id,body)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/tasks/#{task_id}/defect-status"
      huawei_request(:put, url, body: body)
    end

    def generate_pdf(task_id)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/tasks/#{task_id}/pdf-async-job?project_name=#{Time.now.to_i}"
      huawei_request(:put, url)
    end

    def query_generate_pdf(task_id,async_job_id)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/tasks/#{task_id}/async-job/#{async_job_id}"
      huawei_request(:get, url)
    end

    def download_pdf(task_id,query)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/tasks/#{task_id}/pdf-file"
      huawei_download_request(url, query)
    end

    def issue_status(task_id,body)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/defect/issue-status"
      body["taskId"] = task_id
      huawei_request(:post, url, body: body)
    end

    def issue_list_by_filter(task_id,body)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/defect/issue-list-by-filter"
      body["taskId"] = task_id
      huawei_request(:post, url, body: body)
    end

    def issue_filter(task_id,body)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/defect/issue-filter"
      body["taskId"] = task_id
      huawei_request(:post, url, body: body)
    end

    def defect_metric_trend(task_id,query)
      query["task_id"] = task_id
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/history/defect-metric-trend"
      huawei_request(:get, url, params: query)
    end

    def criterion_rule(query)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/rule/criterion-rule/query/#{query["criterion_rule_id"]}"
      huawei_request(:get, url)
    end

    def measure_total(task_id,body)
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/measure/measure-total"
      body["taskId"] = task_id
      huawei_request(:post, url, body: body)
    end

    def related_duplicate_blocks(task_id,query)
      query["taskId"] = task_id
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v1/tasks/#{task_id}/related-duplicate-blocks"
      huawei_request(:get, url, params: query)
    end

    def measure_list(task_id,body)
      body["taskId"] = task_id
      url = "https://codearts-check.#{@region}.myhuaweicloud.com/v2/measure/measure-list"
      huawei_request(:post, url, body: body)
    end



    # huawei_request(:get, url, params: params)
    # huawei_request(:post, url, body: body)
    # huawei_request(:put, url, body: body)
    def huawei_request(method, url, params: {}, body: {})
      begin
        uri = URI.parse(url)

        # GET 专用：拼接 query
        if params.present?
          uri.query = URI.encode_www_form(params)
        end

        Rails.logger.info "Huawei #{method.to_s.upcase} request URL: #{uri}"
        Rails.logger.info "Huawei request params: #{body}" if params.present?
        Rails.logger.info "Huawei request body: #{body}" if body.present?

        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = (uri.scheme == "https")

        # 初始化请求对象
        request_class = case method.to_s.downcase
                        when "get"  then Net::HTTP::Get
                        when "post" then Net::HTTP::Post
                        when "put"  then Net::HTTP::Put
                        else
                          raise ArgumentError, "Unsupported method: #{method}"
                        end

        request = request_class.new(uri.request_uri)

        # 注入头
        @headers.each do |k, v|
          request[k] = v
        end
        # POST / PUT 才需要 JSON body
        if %w[post put].include?(method.to_s.downcase) && body.present?
          request.content_type = "application/json"
          request.body = body.to_json
        end
        response = http.request(request)
        begin
          result = JSON.parse(response.body)
          response_code = if result["error_code"].blank?
                            response.code
                          else
                            "400"
                          end
          [response_code, result]
        rescue JSON::ParserError, TypeError
          [response.code, response.body]
        end

      rescue => e
        Rails.logger.error "Huawei request error: #{e.message}"
        Rails.logger.error e.backtrace.join("\n")
        raise Error, "服务器错误，请联系系统管理员！"
      end
    end


    def huawei_download_request(url,params)
      begin
        uri = URI.parse(url)
        uri.query = URI.encode_www_form(params)
        Rails.logger.info "Huawei download URL: #{uri}"

        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = (uri.scheme == "https")

        # 初始化请求对象
        request = Net::HTTP::Get.new(uri.request_uri)

        # 注入头
        @headers.each do |k, v|
          request[k] = v
        end

        response = http.request(request)

        content_type = response['Content-Type'].to_s
        if content_type.present? && !content_type.include?("application/json")
          return {
            file: true,
            filename: extract_filename(response),
            content_type: content_type,
            data: response.body.force_encoding("ASCII-8BIT")
          }
        end

        begin
          JSON.parse(response.body)
        rescue JSON::ParserError, TypeError
          response.body
        end

      rescue => e
        Rails.logger.error "Huawei request error: #{e.message}"
        Rails.logger.error e.backtrace.join("\n")
        raise Error, "服务器错误，请联系系统管理员！"
      end
    end


    def extract_filename(response)
      if (cd = response['Content-Disposition'])
        matched = cd.match(/filename="?([^"]+)"?/)
        return matched[1] if matched
      end
      "download.bin"
    end

  end
end
