#!/usr/bin/env perl

use v5.18;
use autodie;
use utf8;
use File::Spec;
use JSON;
use JSONLD;
use open ':std', ':encoding(UTF-8)';

my $data;
my $base;
my $j		= JSON->new->pretty(1)->canonical(1)->allow_nonref(1);
my $context	= {};
while (scalar(@ARGV) and $ARGV[0] =~ /^-(\w+)$/) {
	my $flag	= $1;
	shift;
	if ($flag eq 'v') {
		$JSONLD::debug	= 1;
	} elsif ($flag eq 'c') {
		my $file	= shift;
		open(my $fh, '<:utf8', $file);
		my $j	= JSON->new();
		$context	= $j->decode(do { local($/); <$fh> });
	}
}

if (scalar(@ARGV)) {
	my $file	= shift;
	open(my $fh, '<:utf8', $file);
	$data	= $j->decode(do { local($/); <$fh> });
	$base	= 'file://' . File::Spec->rel2abs($file);
} else {
	$data	= $j->decode(do { local($/); <> });
	$base	= 'http://base.example.org/';
}

my $jld			= JSONLD->new(base_iri => IRI->new($base));
my $expanded	= eval { $jld->compact($data, $context) };
if ($@) {
	die $@;
}
print $j->encode($expanded);
