#!/usr/bin/env ruby
# frozen_string_literal: true

# Usage: ruby src/schema.rb TYPE [--graph FILE]
#   TYPE: classes | properties
#   FILE: path to an RDF/Turtle file (default: last data/graph-*.ttl)

require 'bundler/setup'
require 'rdf'
require 'rdf/turtle'
require 'sparql'

type = ARGV.shift
if !%w[classes properties].include?(type)
  abort "Usage: ruby src/schema.rb TYPE [--graph FILE]\n  TYPE: classes | properties"
end

graph_file = nil
if ARGV[0] == '--graph'
  ARGV.shift
  graph_file = ARGV.shift
end

graph_file ||= Dir.glob(File.join('data', 'graph-*.ttl')).sort.last

abort "No graph file found." if graph_file.nil? || !File.exist?(graph_file)

query_file = File.join(__dir__, '..', 'queries', "list_#{type}.sparql")
query = File.read(query_file)

$stderr.puts "Loading #{graph_file}..."
graph = RDF::Graph.load(graph_file)
$stderr.puts "Loaded #{graph.count} triples."

solutions = SPARQL.execute(query, graph)

key = type == 'classes' ? :class : :property
solutions.each do |solution|
  puts solution[key].to_s
end
