use alienfile;
use HTTP::Tiny;
use JSON::PP ();

probe sub { $_[0]->runtime_prop->{ffi_name} = 'onnxruntime' };

share {
    my $nuget = 'https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime';
    my $version = $ENV{ALIEN_ONNXRUNTIME_VERSION} // do {
        my $res = HTTP::Tiny->new->get("$nuget/index.json");
        die "$nuget/index.json: $res->{status} $res->{reason}\n" unless $res->{success};
        my @stable = grep { /^\d+\.\d+\.\d+$/ } @{ JSON::PP::decode_json($res->{content})->{versions} };
        $stable[-1];
    };

    start_url "$nuget/$version/microsoft.ml.onnxruntime.$version.nupkg";
    plugin 'Fetch::HTTPTiny';
    plugin 'Extract::ArchiveZip' => (format => 'zip');

    build sub {
        my ($build) = @_;
        require File::Copy;
        require File::Path;
        my $stage = $build->install_prop->{stage};
        File::Path::make_path("$stage/include", "$stage/lib");
        File::Copy::copy($_, "$stage/include/") or die "copy $_: $!" for glob 'build/native/include/*.h';
        File::Copy::copy($_, "$stage/lib/") or die "copy $_: $!" for glob 'runtimes/linux-x64/native/*.so';
        symlink 'libonnxruntime.so', "$stage/lib/libonnxruntime.so.1" or die "symlink: $!";
        $build->runtime_prop->{version} = $version;
    };

    plugin 'Gather::IsolateDynamic';
    gather sub {
        my ($build) = @_;
        my $prefix = $build->runtime_prop->{prefix};
        $build->runtime_prop->{cflags} = "-I$prefix/include ";
        $build->runtime_prop->{libs} = "-L$prefix/lib -lonnxruntime ";
    };
};
