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

# keila_csv — Entrypoint dispatcher for the Keila CSV tools
#
# Usage:
#   keila_csv keila2csv <keila_export.csv> <output.csv>
#   keila_csv csv2keila <flat_contacts.csv> <keila_import.csv>

COMMANDS = {
  "keila2csv" => "Convert a Keila contact export to a flat CSV\n" \
                 "    (expands the 'data' JSON column into individual columns)",
  "csv2keila" => "Convert a flat CSV to a Keila-importable contact file\n" \
                 "    (packs non-standard columns back into the 'data' JSON column)"
}.freeze

def help
  puts <<~HELP
    Usage:
      keila_csv <command> <input.csv> <output.csv>

    Commands:
      keila2csv   #{COMMANDS['keila2csv']}
      csv2keila   #{COMMANDS['csv2keila']}

    Examples:
      keila_csv keila2csv  export.csv   contacts_flat.csv
      keila_csv csv2keila  contacts.csv keila_import.csv
  HELP
end

command = ARGV.shift

if command.nil? || %w[--help -h help].include?(command)
  help
  exit 0
end

unless COMMANDS.key?(command)
  warn "Error: unknown command '#{command}'"
  warn ""
  help
  exit 1
end

# Re-dispatch to the actual script, passing remaining ARGV through
script = File.join(__dir__, command)
exec script, *ARGV
