require_relative "./lex.rb"
require_relative "./lazylib.rb"

SepRx = /, | |,/
NumRx = /-*\d+/

# return list of inputs or false if auto parse empty (list is from args)
def read_inputs(input)
  input = to_eager_str(read_stdin(input)) if input.respond_to?(:getc)
  !input.empty? && ( Array === input ? input : [input] )
end

def parse_input(inputs)
  return [[], EmptyType, 1] if !inputs

  input_lines = inputs.map{|input| input.lines.map(&:chomp) }

  # is it just numbers?
  if input_lines.all?{|input| input.all?{|line| line =~ /^(#{NumRx}#{SepRx})*#{NumRx}?$/ && line.scan(NumRx).all?{|num| num == num.to_i.to_s } } } &&
      input_lines.flatten.any?{|line| line =~ NumRx }

    nums = input_lines.map{|input|
      input.map{|line|
        to_eager_list(split_non_digits(str_to_lazy_list(line).const).const)
      }
    }
    rank = 3

    if nums.all?{|arg| arg.all?{|line| line.size == 1 } }
      nums = nums.map{|arg| arg.map{|line| line[0] } }
      rank -= 1
    end

    if nums.all?{|arg| arg.size == 1}
      nums = nums.map{|arg| arg[0] }
      rank -= 1
    end

    if nums.size == 1
      nums = nums[0]
      rank -= 1
    end

    [to_lazy_list_rec(nums), IntType, rank]
  else # not numbers
    rank = 3
    if input_lines.all?{|arg| arg.size == 1}
      input_lines = input_lines.map{|arg| arg[0] }
      rank -= 1
    end

    if input_lines.size == 1
      input_lines = input_lines[0]
      rank -= 1
    end

    [to_lazy_list_rec(input_lines), CharType, rank]
  end
end