#!/usr/bin/env perl
use v5.14;

use Getopt::Long;
use HTTP::Tiny;
use Scalar::Util qw(blessed);
use Encode qw(decode_utf8 encode_utf8);

our $VERSION = '0.3.5';

# Assume everything outside is UTF-8
binmode( STDIN,  ":encoding(UTF-8)" );
binmode( STDOUT, ":encoding(UTF-8)" );
binmode( STDERR, ":encoding(UTF-8)" );
@ARGV = map { decode_utf8($_) } @ARGV;

# get command line options
my %OPT;
Getopt::Long::Configure('bundling');
GetOptions(
    \%OPT,
    'help|h|?', 'version|V', 'man', 'ontology', 'prefixes',
    'api=s',
    'format|f=s',
    'query|q=s',
    'ids|i!',
    'language|g=s',
    'color|C!',
    'header!', 'H!',
    'no-execute|n!',
    'no-mediawiki|m!',
    'N!',
    'ignore!',
    'limit=i', '1!', '2!', '3!', '4!', '5!', '6!', '7!', '8!', '9!',
    'default-prefixes!',
    'response=s',    # not documented
    'export=s',
    'force!',
) or exit 1;

# use color by default if output is terminal
$OPT{color_stderr} = $OPT{color} // -t STDERR;    ## no critic
$OPT{color} //= -t STDOUT;                        ## no critic

sub cDefault {
    $OPT{color} ? "\e[0;39m$_[0]\e[0m" : $_[0]    # default
}

sub cBold {
    $OPT{color} ? "\e[1;39m$_[0]\e[0m" : $_[0]    # bold
}

sub cValue {
    $OPT{color} ? "\e[0;32m$_[0]\e[0m" : $_[0]    # green
}

sub cName {
    $OPT{color} ? "\e[0;34m$_[0]\e[0m" : $_[0]    # blue
}

sub cIdentifier {
    $OPT{color} ? "\e[0;33m$_[0]\e[0m" : $_[0]    # yellow
}

sub warning {
    say STDERR $OPT{color_stderr} ? "\e[1;31m$_[0]\e[0m" : $_[0]    # bold red
}

my %NAMESPACES = (

    # standard ontologies
    rdf    => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
    xsd    => 'http://www.w3.org/2001/XMLSchema#',
    rdfs   => 'http://www.w3.org/2000/01/rdf-schema#',
    owl    => 'http://www.w3.org/2002/07/owl#',
    skos   => 'http://www.w3.org/2004/02/skos/core#',
    schema => 'http://schema.org/',
    geo    => 'http://www.opengis.net/ont/geosparql#',
    prov   => 'http://www.w3.org/ns/prov#',

    # Wikibase ontology
    wikibase => 'http://wikiba.se/ontology#',
    wd       => 'http://www.wikidata.org/entity/',
    wdt      => 'http://www.wikidata.org/prop/direct/',
    wds      => 'http://www.wikidata.org/entity/statement/',
    p        => 'http://www.wikidata.org/prop/',
    wdref    => 'http://www.wikidata.org/reference/',
    wdv      => 'http://www.wikidata.org/value/',
    ps       => 'http://www.wikidata.org/prop/statement/',
    psv      => 'http://www.wikidata.org/prop/statement/value/',
    pq       => 'http://www.wikidata.org/prop/qualifier/',
    pqv      => 'http://www.wikidata.org/prop/qualifier/value/',
    pr       => 'http://www.wikidata.org/prop/reference/',
    prv      => 'http://www.wikidata.org/prop/reference/value/',
    wdno     => 'http://www.wikidata.org/prop/novalue/',

    # blazegraph SPARQL extensions
    hint => 'http://www.bigdata.com/queryHints#',
    bd   => 'http://www.bigdata.com/rdf#',
    bds  => 'http://www.bigdata.com/rdf/search#',
    fts  => 'http://www.bigdata.com/rdf/fts#',

    # not used in Wikidata Query Service
    wdata => 'http://www.wikidata.org/wiki/Special:EntityData/',
    cc    => 'http://creativecommons.org/ns#',
);

my $LANGUAGE_PATTERN = qr{^([a-z]+(-[a-zA-Z0-9]+)*)$};

my $ENTITY_PATTERN = qr{^
    (https?://www\.wikidata\.org/
     (wiki|entity|wiki/Special:EntityData)/)?
     (?<id>(q|(Property:)?p)\d+)
$}ix;

my $WIKIDATA_ID_PATTERN = qr{^
    http://www\.wikidata\.org/
    ( entity (/statement)? | reference | value |
      prop (/(statement|qualifier|reference)/value)?)
    /(?<id>.+)
$}x;

my $SITELINK_PATTERN = qr{^
    https?://
    (?<base>
      ( [^.]+. ( wikipedia | wiktionary | wikibooks | wikiquote |
                wikisource | wikinews | wikiversity | wikivoyage )
      | ( commons | species )\.wikimedia
    )\.org)
    /wiki/
    (?<title>.+)
}x;

sub pod_text {
    require Pod::Usage;
    my $text;
    open my $out, '>', \$text;
    Pod::Usage::pod2usage(
        -exit   => 'NOEXIT',
        -output => $out,
        indent  => 2,
        @_
    );
    $text;
}

# execute info mode
if ( $OPT{version} ) {
    say "wdq $VERSION";
    exit;
}
elsif ( $OPT{help} ) {
    my $help = pod_text(
        -msg => cBold("wdq ")
          . cValue("[query]  ")
          . cName("[OPTIONS]")
          . " < query\n"
          . cBold("wdq ")
          . cValue(" lookup  ")
          . cName("[OPTIONS]")
          . " < ids\n"
          . cBold("wdq ")
          . cValue("[lookup] ")
          . cName("[OPTIONS]")
          . " ids...\n",
        -sections => [qw(USAGE OPTIONS)],
    );
    $help =~ s/\n\n  --/\n  --/gm;
    $help =~ s/^      /    /mg;
    if ( $OPT{color} ) {
        $help =~ s/^([a-z]+:)/cBold($1)/mgei;          # headers
        $help =~ s/^(  --.*)$/cName($1)/mge;           # options
        $help =~ s/("[^"\n]+")/cValue($1)/mge;         # strings
        $help =~ s/(<[^>\n]+>)/cIdentifier($1)/mge;    # URLs
    }
    print $help;
    exit;
}
elsif ( $OPT{man} ) {
    my $module = $OPT{color} ? 'Pod::Text::Color' : 'Pod::Text';

    # may fail if pure script installed by hand
    eval "require $module; require App::wdq";          ## no critic
    $module->new->parse_from_file( $INC{'App/wdq.pm'} // $0 );
    exit;
}
elsif ( $OPT{namespaces} ) {
    for my $prefix ( sort keys %NAMESPACES ) {
        printf "%8s: %s\n", $prefix, $NAMESPACES{$prefix};
    }
    exit;
}
elsif ( $OPT{ontology} ) {
    my $help = pod_text(
        -sections => ['WIKIDATA ONTOLOGY'],
        -verbose  => 99,
    );
    $help =~ s/^Wikidata Ontology:\n//;
    $help =~ s/^(    |  )//mg;
    $help =~ s/^([a-z]+)/cBold($1)/mgei;
    $help =~ s/ ([A-Z][A-Za-z]+)/" ".cBold($1)/mge;
    $help =~ s/(<--|-->|--)/cDefault($1)/mge;
    $help =~ s/ ([a-z]+:([a-zA-Z_]+)?|[a-z][a-zA-Z]+)/" ".cName($1)/mge;
    $help =~ s/(<[^ >]+>|@[a-z_]+)/cIdentifier($1)/mge;
    $help =~ s/("[^"\n]+")/cValue($1)/mge;
    print $help;
    exit;
}

# default SPARQL endpoint
$OPT{api} //= 'https://query.wikidata.org/bigdata/namespace/wdq/sparql';

# default output format
$OPT{format} = lc( $OPT{format} // 'simple' );

# read query from STDIN by default
$OPT{query} //= '-';

# add default prefixes by default
$OPT{'default-prefixes'} //= 1;

# include header in output
$OPT{header} //= $OPT{H} ? 0 : 1;

# limit given as single digit option
foreach ( grep { $OPT{$_} } 1 .. 9 ) {
    $OPT{limit} = $_ if !$OPT{limit} or $OPT{limit} > $_;
}

# validate language and set default value if missing
$OPT{language} //= do { my $l = $ENV{LANG} // 'en'; $l =~ s/_.*//; $l };
$OPT{language} = lc( $OPT{language} );
if ( grep { $_ !~ $LANGUAGE_PATTERN } split ",", $OPT{language} ) {
    warning("invalid language(s): $OPT{language}");
    exit 1;
}

# disable all requests
if ( $OPT{N} ) {
    $OPT{'no-mediawiki'} = 1;
    $OPT{'no-execute'}   = 1;
}

my $MODE = !@ARGV ? 'query' : do {
    my $arg = $ARGV[0];
    $arg =~ s/^\s*|\s*$//g;
    if ( $arg =~ /^(query|lookup)$/ ) {
        shift @ARGV;
    }
    elsif ( $arg =~ $ENTITY_PATTERN or $arg =~ $SITELINK_PATTERN ) {
        'lookup';
    }
};

# require only if actually needed
require RDF::Query;

# monkey-patch RDF::Query to keep minimum required version at Ubuntu 14.04 LTS
require version;
if ( version->parse($RDF::Query::VERSION) < version->parse('2.915_01') ) {
    require RDF::Query::Parser::SPARQL;
    *RDF::Query::Node::Resource::as_sparql = sub {
        my $self    = shift;
        my $context = shift || {};
        my $uri     = $self->uri_value;
        my $ns      = $context->{namespaces} || {};
        my %ns      = %$ns;
        foreach my $k ( keys %ns ) {
            no warnings 'uninitialized';
            if ( $k eq '__DEFAULT__' ) {
                $k = '';
            }
            my $v = $ns{$k};
            if ( index( $uri, $v ) == 0 ) {
                my $local = substr( $uri, length($v) );
                if ( $local =~ $RDF::Query::Parser::SPARQL::r_PN_LOCAL ) {
                    my $qname = join( ':', $k, $local );
                    return $qname;
                }
            }
        }
        '<' . URI->new( encode_utf8( $self->uri_value ) )->canonical . '>';
      }
}

my $EXPORTER;
if ( $OPT{export} || $OPT{format} eq 'export' ) {
    $EXPORTER = eval {
        require Catmandu;
        Catmandu->exporter( $OPT{export} // 'JSON', header => $OPT{header} );
    };
    if ($@) {
        warning("option export requires Perl module "
              . "Catmandu::Exporter::$OPT{export}" );
        exit 1;
    }
    elsif ( $OPT{format} !~ /^(ldjson|simple)$/ ) {
        warning("option export overrides option format");
        Catmandu->load();
    }
    $OPT{format} = 'export';
}

sub simple_node {
    if ( !blessed( $_[0] ) ) {
        '';
    }
    elsif ( $_[0]->isa('RDF::Trine::Node::Resource') ) {
        $_[0]->uri_value;
    }
    elsif ( $_[0]->isa('RDF::Trine::Node::Literal') ) {
        $_[0]->literal_value;
    }
    else {
        $_[0]->sse;
    }
}

package App::wdq::Format {

    sub new {
        my $class = shift;
        bless {@_}, $class;
    }

    sub emit {
        my ( $format, $iterator, $vars, $out ) = @_;
        my $data = { out => $out, vars => $vars };
        $format->{pre}->($data) if $format->{pre};
        $iterator->each(
            sub {
                $format->{row}->( $data, $_[0] );
            }
        ) if $format->{row};
        $format->{post}->($data) if $format->{post};
    }
}

sub json_string {
    JSON->new->allow_nonref->encode(shift);
}

my %FORMATS = (

    # SPARQL Query Results JSON
    json => App::wdq::Format->new(
        pre => sub {
            my $o = shift;
            print { $o->{out} }
              "{\n  \"head\": {\n    \"vars\": [",
              join( ", ", map { cName( json_string($_) ) } @{ $o->{vars} } ),
              "]\n  },\n  \"results\": {\n    \"bindings\": [";
        },
        row => sub {
            my ( $o, $row ) = @_;
            print { $o->{out} } $o->{count}++ ? ", {\n" : " {\n";
            my $delim = 0;
            foreach my $v ( @{ $o->{vars} } ) {
                print { $o->{out} } ",\n" if $delim++;
                print { $o->{out} } "      " . cName( json_string($v) ) . ": ";
                my $node = $row->{$v}->as_hashref;
                $node->{'xml:lang'} = delete $node->{lang} if $node->{lang};
                my $json = JSON->new->pretty->canonical->encode($node);
                $json =~ s/^ /      /mg;
                $json =~ s/}\n$/      }/;
                $json =~
                  s/^(\s+"[a-z:]+")\s*:(.*")(,)?$/"$1:".cValue($2).$3/mge;
                print { $o->{out} } "$json";
            }
            print { $o->{out} } "\n    }";
        },
        post => sub {
            my $o = shift;
            print { $o->{out} } " ]\n  }\n}\n";
        }
    ),

    # SPARQL Query Results XML
    xml => 'xml',

    # SPARQL TSV
    tsv => App::wdq::Format->new(
        pre => sub {
            my $o = shift;
            say { $o->{out} } join( "\t", map { "?$_" } @{ $o->{vars} } );
        },
        row => sub {
            my ( $o, $row ) = @_;
            say { $o->{out} } join "\t",
              map { blessed($_) ? $_->as_ntriples : '' }
              map { $row->{$_} } @{ $o->{vars} };
        }
    ),

    # SPARQL CSV
    csv => App::wdq::Format->new(
        pre => sub {
            my $o = shift;
            say { $o->{out} } join cDefault(','),
              map { cName($_) } @{ $o->{vars} }
              if $OPT{header};
        },
        row => sub {
            my ( $o, $row ) = @_;
            say { $o->{out} } join cDefault(','), map {
                my $s = simple_node( $row->{$_} );
                if ( $s =~ /[",\x0A\x0D]/ ) {
                    $s =~ s/"/""/g;
                    $s = "\"$s\"";
                }
                cValue($s)
            } @{ $o->{vars} };
        }
    ),

    # simple JSON key-value structure
    simple => App::wdq::Format->new(
        pre => sub {
            my $o = shift;
            $o->{count} = 0;
            print { $o->{out} } "[";
        },
        row => sub {
            my ( $o, $row ) = @_;
            my $json = JSON->new->pretty->canonical->encode(
                { map { $_ => simple_node( $row->{$_} ) } @{ $o->{vars} } } );
            chomp $json;
            $json =~ s/^/   /mg;
            print { $o->{out} } "," if $o->{count}++;
            print { $o->{out} } "\n", $json;
        },
        post => sub {
            require JSON;
            my $o = shift;
            if ( $o->{count} ) {
                say { $o->{out} } "\n]";
            }
            elsif ( defined $o->{count} ) {
                say { $o->{out} } "]";
            }
            else {
                say { $o->{out} } "[]";
            }
        }
    ),

    # simple line-delimited JSON key-value structure
    ldjson => App::wdq::Format->new(
        row => sub {
            my ( $o, $row ) = @_;
            require JSON;
            say { $o->{out} }
              JSON->new->canonical->encode(
                { map { $_ => simple_node( $row->{$_} ) } @{ $o->{vars} } } );
        }
    ),

    # pipe to Catmandu exporter
    export => App::wdq::Format->new(
        pre => sub {
            my $o = shift;
            $o->{exporter} = $EXPORTER;
        },
        row => sub {
            my ( $o, $row ) = @_;
            $o->{exporter}->add(
                { map { $_ => simple_node( $row->{$_} ) } @{ $o->{vars} } } );
        },
        post => sub {
            $_[0]->{exporter}->commit;
        }
    ),
);

my $format = $FORMATS{ $OPT{format} } // do {
    warning("unknown format: $OPT{format}");
    exit 1;
};

if ( $MODE eq 'lookup' and $format =~ /^(json|xml)$/ ) {
    warning("format $format not supported with method lookup yet!");
    exit 1;
}

sub expand_query {
    my $query = shift;

    if ( $query =~ /^\s*{/m ) {
        $query = "SELECT * WHERE $query";
    }
    elsif ( $query !~ /^[^{]*SELECT/ ) {
        $query = "SELECT * WHERE { $query }";
    }

    if ( $OPT{'default-prefixes'} ) {

        # Add PREFIX for actually used and known prefixes
        my %ns;
        my $ps = join '|', keys %NAMESPACES;
        $ns{$_} = $NAMESPACES{$_} for $query =~ /($ps):[^\/]/mg;
        my @prefixes = map { "PREFIX $_: <$ns{$_}>" } sort keys %ns;
        $query = join "\n", @prefixes, $query;
    }

    $query;
}

sub http_get {
    my ( $base, @query ) = @_;

    state $http = HTTP::Tiny->new(
        default_headers => {
            agent => "wdq/$VERSION"
        }
    );

    my $url = "$base?" . $http->www_form_urlencode( \@query );
    $http->get($url);
}

sub get_qid_from_sitelink {
    my $api   = "https://$_[0]/w/api.php";
    my $title = $_[1];

    my $res = http_get(
        $api,
        action    => 'query',
        prop      => 'pageprops',
        titles    => $title,
        format    => 'json',
        redirects => 1
    );
    return unless $res->{success};

    my $data = JSON->new->decode( $res->{content} );
    my ($page) = values %{ $data->{query}->{pages} };
    return unless $page->{pageprops};
    return $page->{pageprops}->{wikibase_item};
}

sub get_lookup_query {
    my $id = shift;

    my $entity_id;

    if ( $id =~ $ENTITY_PATTERN ) {
        $entity_id = $+{id};
        $entity_id =~ s/Property://i;
    }
    else {
        # URL could be percent-encoded or not, so normalize
        my $uri = URI->new($id);
        if ( $uri and $uri->canonical =~ $SITELINK_PATTERN ) {
            my ( $base, $title ) = ( $+{base}, $+{title} );

            # unescape to UTF-8 octets
            $title =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
            $title = decode_utf8($title);

            if ( $OPT{'no-mediawiki'} ) {
                warning("MediaWiki API disabled");
                exit 1;
            }
            $entity_id = get_qid_from_sitelink( $base, $title );
            unless ($entity_id) {
                warning("Wikidata item not found: $id");
                return;
            }
        }
    }

    unless ($entity_id) {
        warning("unknown identifier: $id");
        return;
    }

    my $uri = "http://www.wikidata.org/entity/" . uc($entity_id);

    return <<SPARQL;
SELECT ?id ?idLabel ?idDescription WHERE {
    BIND(<$uri> AS ?id)
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "$OPT{language}" .
    }
}
SPARQL
}

sub parse_response {
    my ( $json, @map ) = @_;

    require RDF::Trine::Iterator::JSONHandler;
    my $iter = RDF::Trine::Iterator::JSONHandler->new->parse($json);

    unshift @map, sub {
        my $r = $_;
        foreach my $name ( keys %$r ) {
            my $v = $r->{$name};
            next unless $v->isa('RDF::Trine::Node::Resource');
            my $id;
            $id = $+{id} if $v->uri_value =~ $ENTITY_PATTERN;
            $id = $+{id} if $v->uri_value =~ $WIKIDATA_ID_PATTERN;
            $r->{$name} = RDF::Trine::Node::Literal->new($id) if $id;
        }
        $r;
      }
      if $OPT{ids};

    $iter = RDF::Trine::Iterator::smap( $_, $iter ) for @map;

    $iter;
}

if ( $MODE eq 'lookup' ) {
    require URI;
    my $query;
    my $varmap = sub {
        $_->{label}       = delete $_->{idLabel};
        $_->{description} = delete $_->{idDescription};
        $_;
    };
    my $output = {
        out  => \*STDOUT,
        vars => [qw(id label description)]
    };
    my $error = 0;

    my $lookup = sub {
        my $id = shift;
        $id =~ s/^\s+|\s+$//g;    # trim whitespace
        return if $id eq '';      # skip empty lines

        $query = get_lookup_query($id) or return;
        $query = RDF::Query->new( expand_query($query) )->as_sparql;
        if ( $OPT{'no-execute'} ) {
            say $query;
        }
        else {
            my $res = http_get( $OPT{api}, query => $query, format => 'json' );
            if ( $res->{success} ) {
                my $iter = parse_response( $res->{content}, $varmap );
                unless ( $output->{head} ) {
                    $output->{head} = 1;
                    $format->{pre}->($output) if $format->{pre};
                }
                $format->{row}->( $output, $iter->next ) if $iter->peek;
            }
            elsif ( !$OPT{ignore} ) {
                warning("not found: $id");
                $error = 1;
            }
        }
    };

    my $limit = $OPT{limit} // 0;
    if (@ARGV) {
        foreach (@ARGV) {
            $lookup->($_);
            last if !--$limit;
        }
    }
    else {
        while (<>) {
            $lookup->($_);
            last if !--$limit;
        }
    }

    if ( !$OPT{'no-execute'} and $format->{post} ) {
        $format->{post}->($output);
    }
    exit $error;
}

my ( $query, $sparql, $variables );
{
    local $/ = undef;
    if ( $OPT{query} eq '-' ) {
        $query = <STDIN>;
    }
    elsif ( -f $OPT{query} or $OPT{query} !~ /[$\?\{]/ ) {
        open my $fh, '<', $OPT{query}
          or die "failed to open file " . $OPT{query};
        $query = <$fh>;
        open my $fh;
    }
    else {
        $query = $OPT{query};
    }

    $query  = expand_query($query);
    $sparql = do {
        my $q = RDF::Query->new($query);
        unless ($q) {
            if ( $OPT{'force'} ) {
                warning("SPARQL query seems invalid");
                undef;
            }
            else {
                warning("invalid SPARQL query");
                exit 1;
            }
        }
    };
}

if ($sparql) {
    $variables = [ map { $_->name } @{ $sparql->parsed->{variables} } ];
    $query = $sparql->as_sparql;
}

# LIMIT and OFFSET are always last so we can safely use regexp here
if ( $OPT{limit} ) {
    $query =~ s/\n*LIMIT\s+\d+(\s+OFFSET\s+\d+)?\s*$/$1/sm;
    $query .= "\nLIMIT $OPT{limit}";
}

if ( $OPT{'no-execute'} ) {
    chomp $query;
    say $query;
    exit;
}

my $res = do {
    if ( $OPT{response} ) {
        {
            content => do { local ( @ARGV, $/ ) = $OPT{response}; <> },
            success => 1,
        };
    }
    else {
        http_get(
            $OPT{api},
            query  => $query,
            format => $format eq 'xml' ? $format : 'json'
        );
    }
};

if ( !$res->{success} ) {
    say STDERR $res->{content};
    exit 1;
}

if ( $format eq 'xml' ) {
    if ( $OPT{ids} ) {
        warning("option ids not supported for format xml yet!");
    }
    else {
        say $res->{content};
        exit;
    }
}

# convert SPARQL JSON response
my $iterator = parse_response( $res->{content} );

# convert result
if ( $OPT{ignore} || $iterator->peek ) {
    my $vars = $variables // sort keys %{ $iterator->peek };
    $format->emit( $iterator, $vars, \*STDOUT );
}
else {
    warning("not found");
    exit 1;
}

__END__

=head1 NAME

wdq - command line access to Wikidata Query Service

=head1 USAGE

Access L<Wikidata Query Service|https://query.wikidata.org/> via command line.
In C<query> mode (default), a SPARQL query is read from STDIN or option
C<--query>.  Default namespaces are and C<SELECT> clause are added if missing.
In C<lookup> mode, Wikidata entity ids, URLs, or Wikimedia project URLs are
read from STDIN or as command line arguments to look up label and description.

=head1 EXAMPLES

  # get all parts of the solar system
  wdq -q '?c wdt:P361 wd:Q544'
  wdq -q '{ ?c wdt:P361 wd:Q544 }'                # equivalent
  wdq -q 'SELECT * WHERE { ?c wdt:P361 wd:Q544 }' # equivalent

  # look up label and description
  wdq Q1
  wdq lookup Q1             # equivalent
  echo Q1 | wdq lookup      # equivalent

=head1 OPTIONS

=over

=item --query|-q QUERY

Query or query file (C<-> for STDIN as default)

=item --format|-f FORMAT

Output format. Supported formats include C<json>, C<xml>, C<tsv>, and C<csv>
SPARQL result format, C<simple> for flat JSON without language tags (default),
and C<ldjson> for line delimited flat json. For more flexible output options
pipe to another tool such as L<jq|http://stedolan.github.io/jq/>,
L<miller|http://johnkerl.org/miller/>, and
L<catmandu|https://github.com/LibreCat/Catmandu>. If L<Catmandu> is installed,
its exporters can directly be used with option C<export>.

=item --limit INTEGER

Add or override a LIMIT clause to limitate the number of results. Single-digit
options such as C<-1> can also be used to also set a limit.

=item --no-header|-H

Exclude header in CSV output or other exporter.

=item --export EXPORTER

Use a L<Catmandu> exporter as output format, for instance C<XLS> (Excel) and
Markdown tables (C<Table>). The following produce same output:

  wdq --export Foo
  wdq --format ldjson | catmandu convert to Foo

Use Catmandu config file (C<catmandu.yml>) to further configure export.

=item --ids|-i

Abbreviate Wikidata identifier URIs as strings (except output format C<xml>).

=item --language|-g

Language to query labels and descriptions in. Set to the locale by default.
This option is currentl only used on lookup mode.

=item --ignore

Ignore empty results instead of issuing warning and exit code.

=item --color|-C

By default output is colored if writing to a terminal. Disable this with
C<--no-color> or force color with C<--color> or C<-C>.

=item --api URL

SPARQL endpoint. Default value:
C<https://query.wikidata.org/bigdata/namespace/wdq/sparql>

=item --no-mediawiki|-m

Don't query MediaWiki API to map URLs to Wikidata items.

=item --no-execute|-n

Don't execute SPARQL queries but show them in expanded form. Useful to
validate and pretty-print queries. MediaWiki API requests may be 

=item -N

Don't execute any queries. Same as C<--no-mediawiki --no-execute>.

=item --help|-h|-?

Show usage help

=item --ontology

Show information about the Wikidata Ontology

=item --prefixes

Show the default prefixes

=item --no-default-prefixes

Don't add default namespace prefixes to the SPARQL query

=item --man

Show detailled manual

=item --version|-V

Show version if this script

=back

=head1 WIKIDATA ONTOLOGY

  Entity (item/property)
   wd:Q_ <-- owl:sameAs --> wd:Q_
         --> rdfs:label, skos:altLabel, schema:description "_"@_
         --> schema:dateModified, schema:version
         --> wdt:P_ "_", URI, _:blank
         --> p:P_ Statement

  Item
   wd:Q_ <-- schema:about <http://_.wikipedia.org/wiki/_>
                          --> schema:inLanguage, wikibase:badge

  Property
   wd:P_ --> wikibase:propertyType PropertyType
         --> wkibase:directClaim        wdt:P_
         --> wikibase:claim             p:P_
         --> wikibase:statementProperty ps:P_
         --> wikibase:statementValue    psv:P_
         --> wikibase:qualifier         pq:P_
         --> wikibase:qualifierValue    pqv:P_
         --> wikibase:reference         pr:P_
         --> wikibase:referenceValue    prv:P_
         --> wikibase:novalue           wdno:P_

  PropertyType
   wikibase: String, Url, WikibaseItem, WikibaseProperty, CommonsMedia,
             Monolingualtext, GlobeCoordinate, Quantity, Time


  Statement
   wds:_ --> wikibase:rank Rank
         --> a wdno:P_
         --> ps:P_ "_", URI, _:blank
         --> psv:P_ Value
         --> pq:P_ "_", URI, _:blank
         --> pqv:P_ Value
         --> prov:wasDerivedFrom Reference

  Reference
   wdref:_ --> pr:P_ "_", URI
           --> prv:P_ Value

  Rank
   wikibase: NormalRank, PreferredRank, DeprecatedRank, BestRank

  Value (GlobecoordinateValue/QuantityValue/TimeValue)
   wdv:_ --> wikibase: geoLatitude, geoLongitude, geoPrecision, geoGlobe URI
         --> wikibase: timeValue, timePrecision, timeTimezone, timeCalendarModel
         --> wikibase: quantityAmount, quantityUpperBound, quantityLowerBound,
                       quantityUnit URI

=head1 COPYRIGHT AND LICENSE

Copyright by Jakob Voss C<voss@gbv.de>

Based on a PHP script by Marius Hoch C<hoo@online.de>
at L<https://github.com/mariushoch/asparagus>.

Licensed under GPL 2.0+

=cut
