#!/usr/bin/env perl
use strict;
use warnings;
use Path::Tiny;
use HTTP::Tiny;
use YAML::PP;
use JSON::Schema::Modern;

my %files = (
  # metaschema for json schemas contained within openapi documents
  'oas/dialect/base.schema.json'  => 'https://spec.openapis.org/oas/3.1/dialect/base',

  # vocabulary definition
  'oas/meta/base.schema.json'  => 'https://spec.openapis.org/oas/3.1/meta/base',

  # openapi document schema + custom json schema dialect
  #'oas/schema-base.json' => 'https://spec.openapis.org/oas/3.1/schema-base',
  'oas/schema-base.json' => 'https://spec.openapis.org/oas/3.1/schema-base/2021-09-28',

  # the main openapi document schema
  #'oas/schema.json' => 'https://spec.openapis.org/oas/3.1/schema',
  'oas/schema.json' => 'https://spec.openapis.org/oas/3.1/schema/2021-09-28',
);

foreach my $target (keys %files) {
  my $source = $files{$target};
  $target = path('share', $target);
  $target->parent->mkpath;

  my $response = HTTP::Tiny->new->get($source);
  die "Failed to fetch $source: $response->{status} $response->{reason}" if not $response->{success};

  $target->spew($response->{content});
}

my $yaml = YAML::PP->new(boolean => 'JSON::PP');
my $js = JSON::Schema::Modern->new(validate_formats => 1);
$js->add_schema($files{$_} => $yaml->load_file('share/'.$_)) foreach keys %files;

foreach my $uri (values %files) {
  print "# validating $uri\n" if $ENV{DEBUG};

  my $document = $js->_fetch_from_uri($uri)->{document};
  my $result = $js->evaluate($document->schema, $document->metaschema_uri);

  die $js->_json_decoder->pretty->encode($result) if not $result;
}
