#!/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', 'countries.ttl'))

output = File.open(File.join('data', 'countries_wikidata.ttl'), 'w')
review = File.open(File.join('data', 'countries_wikidata_review.ttl'), 'w')

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

output << ttl_prefixes
review << ttl_prefixes

graph.query([nil, RDF.type, SCHEMA.Country]) 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(COUNTRY.to_s, '')
  $stderr.puts label.to_ntriples
  
  solutions = WIKIDATA.query(<<~SPARQL)
    SELECT DISTINCT ?country ?geoNamesID WHERE {
      ?country rdfs:label #{label.to_ntriples} .
      ?country wdt:P31/wdt:P279* wd:Q6256 .
      ?country wdt:P1566 ?geoNamesID .
    }
  SPARQL

  case solutions.size
  when 0
    review.puts "# No Wikidata entity found for #{label}"
    review.puts "country:#{local_name} rdfs:comment \"No Wikidata entity found\" ."
    review.puts
  when 1
    sol = solutions.first
    wd_id = get_wd_name(sol[:country].to_s)
    output.puts "country:#{local_name} schema:sameAs #{wd_id} ;"
    output.puts "  schema:sameAs geo:#{sol[:geoNamesID]} ."
    output.puts
  else
    review.puts "# Multiple Wikidata entities found for #{label} — remove all but one:"
    solutions.each do |sol|
      wd_id = get_wd_name(sol[:country].to_s)
      review.puts "country:#{local_name} schema:sameAs #{wd_id} ;"
      review.puts "  schema:sameAs geo:#{sol[:geoNamesID]} ."
    end
    review.puts
  end
end

output.close
review.close
