#!/usr/bin/perl

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use JSON::XS;
use FileHandle;
use XML::XPath;
use XML::Hash::XS;
use JSON::Validator;
use JSON::Validator::Schema::Draft7;
use Text::CSV::Easy(qw/csv_build csv_parse/);

my $jv = JSON::Validator->new();

my $schema = JSON::Validator::Schema::Draft7->new('file://contract_schema.json');

my $file = shift @ARGV or die "requires JSON file";
my $fh   = FileHandle->new( $file, 'r' );
my $json;
read $fh, $json, -s $fh;
$fh->close;

my $href = JSON::XS::decode_json($json);
my $xml  = hash2xml($href);
my $xp   = XML::XPath->new( 'xml' => $xml );

my $errs = [ $jv->validate( $href, $schema ) ];
if ( defined $errs and scalar @{$errs} > 0 ) {
    foreach my $err ( @{$errs} ) {
        my $path = $err->path;
        if ( $path =~ m/[0-9]/ ) {
            $path =~ s!([0-9])!$1+1!eg;
            $path =~ s!/([0-9])![$1]!g;
        }
        my $text = "'" . $xp->getNodeText( '/root' . $path ) . "'";
        print STDERR $path . " - [ $text ] - " . $err->message . "\n";
    }
    exit 1;
} else {
    print STDERR "ok\n";
    exit 0;
}
