#!/usr/bin/env ruby

require 'rdf'
require 'rdf/turtle'
require_relative 'database'
require_relative 'vocabularies'
require_relative 'migrants'

graph = RDF::Graph.load(File.join('data', 'religions.ttl'))

output = File.open(File.join('data', 'religions_wikidata.ttl'), 'w')
review = File.open(File.join('data', 'religions_wikidata_review.ttl'), 'w')

ttl_prefixes = "#{prefixes(:wd, :wdt, :rdfs, :schema, :religion)}\n\n"

output << ttl_prefixes
review << ttl_prefixes

graph.query([nil, RDF.type, TM.Religion]) do |stmt|
  subject = stmt.subject
  label_stmt = graph.query([subject, RDFS.label, nil]).first
  next unless label_stmt

  label = label_stmt.object
  local_name = subject.to_s.sub(RELIGION.to_s, '')
  $stderr.puts label.to_ntriples

  solutions = WIKIDATA.query(<<~SPARQL)
    SELECT DISTINCT ?religion WHERE {
      ?religion rdfs:label #{label.to_ntriples} .
      ?religion wdt:P31/wdt:P279* wd:Q9174 .
    }
  SPARQL
  case solutions.size
  when 0
    review.puts "# No Wikidata entity found for #{label}"
    review.puts "religion:#{local_name} rdfs:comment \"No Wikidata entity found\" ."
    review.puts
  when 1
    wd_id = get_wd_name(solutions.first[:religion].to_s)
    output.puts "religion:#{local_name} schema:sameAs #{wd_id} ."
  else
    review.puts "# Multiple Wikidata entities found for #{label} — remove all but one:"
    solutions.each do |solution|
      wd_id = get_wd_name(solution[:religion].to_s)
      review.puts "religion:#{local_name} schema:sameAs #{wd_id} ."
    end
    review.puts
  end
end

output.close
review.close
