#!/usr/bin/ruby -w

class Result
  attr_accessor :version, :result, :time, :guess, :explanation
  def to_s
    "#{@version} #{@result} #{@time} #{@guess} #{@explanation}"
  end
end

previous = {}
IO::read(ARGV[0]).each_line do |l|
  l.chomp!
  r = Result::new
  p, r.version, r.result, r.time, r.guess, r.explanation = l.split(' ', 6)
  if r.explanation.nil?
    r.explanation = ""
  end
  # cleanup old explanations
  r.explanation.gsub!(/ NEWFAIL$/ ,'')
  previous[p] = r 
end

IO::read(ARGV[1]).each_line do |l|
  l.chomp!
  r = Result::new
  pkg, r.version, r.result, r.time, r.guess, r.explanation = l.split(' ', 6)
  r.explanation = "TODO" if r.explanation.nil?
  if previous[pkg].nil?
    r.explanation += " NEWFAIL"
  else
    prev = previous[pkg]
    if prev.explanation != "TODO"
      r.explanation = prev.explanation
      r.explanation.gsub!(/RECHECK[^\s]*/,'')
      r.explanation.gsub!(/NEWFAIL/, '')
      r.explanation.gsub!(/\s+/, ' ')
      r.explanation += " RECHECK"
      r.explanation += " RECHECK_VERSION" if r.version != prev.version
      r.explanation += " RECHECK_GUESS" if r.guess != prev.guess
      nt = r.time.to_f
      ot = prev.time.to_f
      m = [ nt, ot ].min.to_f
      ratio = (nt - ot).abs.to_f
      if m < 30
        p = 1.0
      elsif m < 100
        p = 0.6
      elsif m < 300
        p = 0.4
      else
        p = 0.2
      end
      if (ratio/m) >= p
        r.explanation += " RECHECK_TIME(#{nt.to_i}/#{ot.to_i})"
      end
    end
    previous.delete(pkg)
  end
  puts "#{pkg} #{r}"
end
File::open('no-longer-fails', 'w') do |f|
  previous.each_pair do |pkg, val|
    f.puts pkg + ' ' + val.to_s
  end
end

