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

$LOAD_PATH.unshift(File.expand_path("../lib", __dir__))

require "optparse"
require "reportgen/client"
require "reportgen/fetcher"
require "reportgen/renderer"
require "reportgen/exporter"
require "reportgen/delivery"

command = ARGV.shift

options = { client: nil, month: nil }
OptionParser.new do |parser|
  parser.on("--client CLIENT") { |v| options[:client] = v }
  parser.on("--month MONTH") { |v| options[:month] = v }
end.parse!(ARGV)

unless options[:client] && options[:month]
  warn "usage: reportgen <generate|deliver|export> --client CLIENT --month MONTH"
  exit 1
end

client = Reportgen::Client.new(client_id: options[:client])
fetcher = Reportgen::Fetcher.new(client: client)
records = fetcher.fetch_records(client: options[:client], month: options[:month])

case command
when "generate"
  html = Reportgen::Renderer.new.render(records: records, client: options[:client])
  puts html
when "export"
  csv = Reportgen::Exporter.new.export(records: records)
  puts csv
when "deliver"
  html = Reportgen::Renderer.new.render(records: records, client: options[:client])
  Reportgen::Delivery.new.deliver(report_html: html, client: options[:client])
else
  warn "unknown command: #{command.inspect}"
  exit 1
end
