require 'cgi'

namespace :artist do
  desc 'Find and fix uncorrect mbid'
  task :correct => :environment do
    Artist.where( :approved => nil ).each do |artist|
      puts "Artist: "+artist.name
      bh_albums = artist.albums.map{ |a| a.name.scan(/[a-zA-Z0-9]/).join() }
      tmp = LastFM::Artist.get_top_albums( :artist => artist.name )['topalbums']
      if tmp['album'].nil?
        tmp['album'] = []
      elsif tmp['album'].is_a? Hash
        tmp['album'] = [tmp['album']]
      end
      lastfm_albums = tmp['album'].map do |a|
        a['name'].scan(/[a-zA-Z0-9]/).join()
      end
      if (bh_albums & lastfm_albums).empty?
        puts "Result: No intersection"
        best_candidate = nil
        best_intersection = 0
        MusicBrainz::Artist.search(artist.name.gsub(/\!/, '')).each do |candidate|
          candidate = MusicBrainz::Artist.find(candidate[:mbid])
          candidate_albums = candidate.release_groups.map{ |a| a.title.scan(/[a-zA-Z0-9]/).join() }
          if (candidate_albums & lastfm_albums).length > best_intersection
            best_intersection = (candidate_albums & lastfm_albums).length
            best_candidate = candidate.id
          end
        end
        if best_candidate.nil?
          puts "No better candidate found (now: "+artist.mbid.to_s+")\n\n"
          artist.approved = 0
          artist.save
        else
          puts "Better candidate found: "+best_candidate+" (now: "+artist.mbid.to_s+")\n\n"
          artist.approved = 2
          artist.save
        end
      else
        artist.approved = 1
        artist.save
        puts "Result: OK\n\n"
      end
      sleep 1
    end
  end
end