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

# ATTENTION DISTRO REPACKAGERS: do NOT use fresh copies of these files
# from their source; it is important to include the original versions
# of the files as they were packaged with this cpan distribution, or
# surprising behaviour may occur.

my %files = (
  'draft2020-12/meta/applicator.json'     => 'https://json-schema.org/draft/2020-12/meta/applicator',
  'draft2020-12/meta/content.json'        => 'https://json-schema.org/draft/2020-12/meta/content',
  'draft2020-12/meta/core.json'           => 'https://json-schema.org/draft/2020-12/meta/core',
  'draft2020-12/meta/format-annotation.json' => 'https://json-schema.org/draft/2020-12/meta/format-annotation',
  'draft2020-12/meta/format-assertion.json' => 'https://json-schema.org/draft/2020-12/meta/format-assertion',
  'draft2020-12/meta/meta-data.json'      => 'https://json-schema.org/draft/2020-12/meta/meta-data',
  'draft2020-12/meta/unevaluated.json'    => 'https://json-schema.org/draft/2020-12/meta/unevaluated',
  'draft2020-12/meta/validation.json'     => 'https://json-schema.org/draft/2020-12/meta/validation',
  'draft2020-12/output/schema.json'       => 'https://json-schema.org/draft/2020-12/output/schema',
  'draft2020-12/schema.json'              => 'https://json-schema.org/draft/2020-12/schema',

  'draft2019-09/meta/applicator.json'     => 'https://json-schema.org/draft/2019-09/meta/applicator',
  'draft2019-09/meta/content.json'        => 'https://json-schema.org/draft/2019-09/meta/content',
  'draft2019-09/meta/core.json'           => 'https://json-schema.org/draft/2019-09/meta/core',
  'draft2019-09/meta/format.json'         => 'https://json-schema.org/draft/2019-09/meta/format',
  'draft2019-09/meta/meta-data.json'      => 'https://json-schema.org/draft/2019-09/meta/meta-data',
  'draft2019-09/meta/validation.json'     => 'https://json-schema.org/draft/2019-09/meta/validation',
  'draft2019-09/output/schema.json'       => 'https://json-schema.org/draft/2019-09/output/schema',
  'draft2019-09/schema.json'              => 'https://json-schema.org/draft/2019-09/schema',

  'draft7/schema.json' => 'http://json-schema.org/draft-07/schema#',
);

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 $js = JSON::Schema::Modern->new(validate_formats => 1);
foreach my $uri (values %files) {
  print "# validating $uri\n" if $ENV{DEBUG};

  my $result = $js->_fetch_from_uri($uri)->{document}->validate;
  die $js->_json_decoder->pretty->encode($result) if not $result;
}
