#!/usr/bin/ruby

require 'search_ui'
require 'tins/terminal'
require 'amatch'
include SearchUI


choices = ARGV
exit if choices.empty?

found = Search.new(
  match: -> answer {
    matcher = Amatch::PairDistance.new(answer.downcase)
    matches = choices.map { |n| [ n, -matcher.similar(n.downcase) ] }.
      select { |_, s| s < 0 }.sort_by(&:last).map(&:first)
    matches.empty? and matches = choices
    matches.first(Tins::Terminal.lines - 1)
  },
  query: -> _answer, matches, selector {
    matches.each_with_index.
    map { |m, i| i == selector ? "→ " + Search.on_blue(m) : "  " + m } * ?\n
  },
  found: -> _answer, matches, selector {
    matches[selector]
  },
  output: STDOUT
).start and puts found