#!/usr/bin/env ruby
# frozen_string_literal: true

# kbs2-snip: quickly select and run a code snippet stored in kbs2 using a fuzzy selector
# By default, selecta is used as the fuzzy selector.

require "open3"
require "optparse"
require "json"

abort "Fatal: Not being run as a subcommand?" unless ENV.key? "KBS2_SUBCOMMAND"

trap(:INT) { exit! }

options = { print: false }
OptionParser.new do |opts|
  opts.banner = "Usage: kbs2 snip [-p] record"

  opts.on "-p", "--[no-]print", "print the snippet instead of running it" do |o|
    options[:print] = o
  end
end.parse!

config = JSON.parse `kbs2 config dump`

chooser = config.dig("commands", "ext", "snip", "chooser") || "selecta"

unstructureds = `kbs2 list -k unstructured`.split
snippets = unstructureds.filter_map do |label|
  record = JSON.parse `kbs2 dump -j #{label}`
  contents = record["body"]["fields"]["contents"]

  ["#{label} - #{contents[8..]}", contents[8..]] if contents.start_with? "snippet:"
end.to_h

output, = Open3.capture2 chooser, stdin_data: snippets.keys.join("\n")
selection = output.chomp
code = snippets[selection]

return unless code

if options[:print]
  puts code
else
  exec code
end
