#!/usr/bin/ruby.ruby3.4 
# resolve bin path, ignoring symlinks
require "pathname"
bin_file = Pathname.new(__FILE__).realpath

# add self to libpath
$:.unshift File.expand_path("../../lib", bin_file)

require 'churn/calculator'
require 'churn/version'
require 'main'
require 'yaml'

#example usage. In the root of a project 'churn', or 'churn --help'
Main do
  option('minimum_churn_count', 'c') do
    argument :required
    cast :int
    default 3
  end

  option('yaml', 'y') do
    cast :boolean
    default false
  end

  option('ignore_files', 'i') do
    cast :string
    argument :optional
    default ''
  end

  option('report', 'r') do
    cast :string
    argument :optional
    default ''
  end

  option('name', 'n') do
    cast :string
    argument :optional
    default ''
    description 'name is required if remotely reporting churn results. If available as a github project, pass name in the form of username/project_name'
  end

  option('start_date', 's') do
    cast :string
    argument :optional
    default ''
  end

  option('data_directory', 'd') do
    cast :string
    argument :optional
    default ''
  end

  #grrr h is already taken by --help / -h so whent with 'p'
  option('past_history', 'p') do
    cast :string
    argument :optional
    default ''
  end

  option('extension', 'e') do
    cast :string
    argument :optional
    default ''
  end

  option('prefix', 'f') do
    cast :string
    argument :optional
    default ''
  end

  option('version', 'v') do
    cast :boolean
    argument :optional
    default false
  end

  def report_churn(output_string)
    options = {
      minimum_churn_count: params['minimum_churn_count'].value,
      ignore_files: params['ignore_files'].value,
      start_date: params['start_date'].value,
      data_directory: params['data_directory'].value,
      history: params['past_history'].value,
      report: params['report'].value,
      name: params['name'].value,
      file_extension: params['extension'].value,
      file_prefix: params['prefix'].value,
    }
    if params['version'].value
      puts Churn::VERSION
      return
    end

    result = Churn::ChurnCalculator.new(options).report(output_string)
    if output_string
      result
    else
      YAML::dump(result)
    end
  end

  def run
    report = report_churn(!params['yaml'].value)
    puts report
  end
end
