#! /usr/bin/env ruby

# frozen_string_literal: true

LKP_SRC = ENV['LKP_SRC'] || File.dirname(File.dirname(File.realpath($PROGRAM_NAME)))

require 'yaml'
require 'json'
require 'optparse'

require "#{LKP_SRC}/lib/hash"
require "#{LKP_SRC}/lib/load_file"
require "#{LKP_SRC}/lib/scheduler_client"

def die(msg)
  puts msg
  exit
end

index = nil
data = nil
show_type = nil
select_field = ''
option_hash = {}

options = OptionParser.new do |opts|
  opts.banner = 'Usage: cci search -i $index -d $search'
  opts.separator '    search info from es db by dsl'
  opts.separator '    eg.1: cci search -i jobs -d \'{"_source": ["suite", "id", "job_stage"]}\''
  opts.separator '    eg.2: cci search -i jobs -d \'{"query": {"term": {"suite": "borrow"}}, "_source": ["id"]}\''
  opts.separator 'options:'

  opts.on('-i', '--index <index>', 'search es from which index') do |i|
    index = i
  end
  opts.on('-d', '--data <data>', 'HTTP POST search data') do |d|
    data = d
  end
  opts.on('-s', '--show_type <show_type>', 'search show type: json or array') do |s|
    show_type = s
  end
  opts.on('-h', '--help', 'show this message') do
    die options
  end
end

die(options) if ARGV.empty?
options.parse!(ARGV)
die("unknow args input, please check it: #{ARGV}") unless ARGV.empty?

hash = load_my_config
option_hash['cci_credentials'] = { 'my_account' => hash['my_account'], 'my_token' => hash['my_token'] }
DATA_API_HOST ||= hash['DATA_API_HOST'] || hash['SCHED_HOST']
DATA_API_PORT ||= hash['DATA_API_PORT'] || '20003'

raise 'Please input search index: -i $index'      unless index
raise 'Please input search data: -d $data'        unless data
raise 'Please configure DATA_API_HOST'            unless DATA_API_HOST

search_dsl = JSON.parse(data)
option_hash['query'] = search_dsl
if search_dsl.key?('_source') && !search_dsl['_source'].empty?
  show_type = 'array' if show_type.nil?
  select_field = search_dsl['_source']
elsif show_type.nil?
  show_type = 'json'
end

dataapi_client = DataApiClient.new(DATA_API_HOST, DATA_API_PORT)
response = dataapi_client.es_search(index, option_hash.to_json)
response = JSON.parse(response)
die(response['error_msg']) if response['error_msg']

if show_type == 'json'
  puts JSON.pretty_generate(response)
else
  results = []
  response['hits']['hits'].each do |source|
    results << source['_source']
  end
  die('search results is empty') if results.empty?
  format_print(results, select_field)
end