:- module(example_data, [example_file/2, example_file_present/1]).
:- use_module(library(error)).
:- use_module(library(filesex)).
:- use_module(library(lists)).
:- use_module(library(zlib)).
:- use_module(library(crypto), [crypto_file_hash/3]).
:- use_module(library(http/http_open)).
:- use_module(library(http/http_ssl_plugin)).

/** <module> The data files of the examples, downloaded once

The safetensors files the examples read are not in the repository: they are assets of a
GitHub release of their own, examples-data-1, each gzipped, and the first example to need one
downloads it into the cache, where it stays, checked against its SHA-256.

    example_file(+Name, -File)
        File is the data file Name: the one beside this file, where a script of examples/
        wrote it (classifier.py, detector.py, mnist.py), else the one of the cache, else
        the asset, downloaded and unpacked into the cache first.
    example_file_present(+Name)
        Name is beside this file or in the cache: example_file/2 would not download it.

The cache is the flag example_data_directory, by default array_examples under $XDG_CACHE_HOME
or ~/.cache; deleting it is always safe. A file is unpacked under a temporary name, checked,
then renamed, so that an interrupted download leaves nothing.

The assets are those of the files the scripts write: when one of them is written again, its
asset is replaced in a new release, release/1 and sha256/2 below changed with it.
*/

:- create_prolog_flag(example_data_directory, '', [type(atom), keep(true)]).

% release(-Tag): the GitHub release holding the assets.
release('examples-data-1').

% sha256(?Name, ?Hash): the files of the release and the SHA-256 of each, unpacked.
sha256('classifier_weights.safetensors',
       '64bb367b9c92eb2aa91ae2160e3b63f3a5c68060ff95a5ba629fdfa395ff0a26').
sha256('classifier_inputs.safetensors',
       '93f2622cde7b80e0dc1915b2c11f1245d670fda2edf46ee40306cdca06e2bede').
sha256('detector_weights.safetensors',
       'd686e64f4c7445ae8a3ff19138f395bde6e4277b406b2020387cbf0353f7486a').
sha256('detector_pages.safetensors',
       'dd37e0d061c3fceab1d0abb2d74fca58e1ea0b22dc32b768ee0990c92c4548a6').
sha256('mnist.safetensors',
       '010e06010263f22fd8f0932713c065b2be21ab74c2755fd7b34a47af1bec4432').

example_file(Name, _), \+ sha256(Name, _) =>
   must_be(atom, Name),
   domain_error(example_data_file, Name).
example_file(Name, File), present(Name, File0) => File = File0.
example_file(Name, File) => download(Name, File).

example_file_present(Name) :-
   present(Name, _).

% present(+Name, -File): the file Name beside this file, else in the cache.
present(Name, File) :-
   (  local_file(Name, File)
   ;  cache_file(Name, File)
   ),
   exists_file(File), !.

local_file(Name, File) :-
   module_property(example_data, file(Here)),
   file_directory_name(Here, Dir),
   directory_file_path(Dir, Name, File).

cache_file(Name, File) :-
   cache_directory(Dir),
   release(Tag),
   atomic_list_concat([Dir, Tag, Name], /, File).

cache_directory(Dir), current_prolog_flag(example_data_directory, D), D \== '' => Dir = D.
cache_directory(Dir), getenv('XDG_CACHE_HOME', Home), Home \== '' =>
   directory_file_path(Home, array_examples, Dir).
cache_directory(Dir) =>
   expand_file_name('~/.cache', [Home]),
   directory_file_path(Home, array_examples, Dir).

% download(+Name, -File): the asset of Name, unpacked into the cache file File.
download(Name, File) :-
   release(Tag),
   format(atom(URL), "https://github.com/kwon-young/array/releases/download/~w/~w.gz",
          [Tag, Name]),
   cache_file(Name, File),
   file_directory_name(File, Dir),
   make_directory_path(Dir),
   thread_self(Me), thread_property(Me, id(Id)),
   current_prolog_flag(pid, Pid),
   format(atom(Tmp), "~w.~w.~w.tmp", [File, Pid, Id]),
   print_message(informational, format("Downloading ~w", [URL])),
   catch(unpack(URL, Tmp), E, (delete_tmp(Tmp), throw(E))),
   crypto_file_hash(Tmp, Hash, [algorithm(sha256), encoding(octet)]),
   sha256(Name, Expected),
   checked(Hash, Expected, URL, Tmp, File).

% checked(+Hash, +Expected, +URL, +Tmp, +File): Tmp renamed File if its hash is the one
% expected, else deleted and an error.
checked(Hash, Expected, _, Tmp, File), Hash == Expected =>
   rename_file(Tmp, File).
checked(Hash, Expected, URL, Tmp, _) =>
   delete_tmp(Tmp),
   throw(error(checksum_error(URL, Expected, Hash), _)).

unpack(URL, Tmp) :-
   setup_call_cleanup(
       http_open(URL, In, []),
       setup_call_cleanup(
           ( stream_pair(In, Read, _),     % http_open/3 may give a pair
             zopen(Read, Z, [format(gzip), close_parent(false)]) ),
           setup_call_cleanup(
               open(Tmp, write, Out, [type(binary)]),
               copy_stream_data(Z, Out),
               close(Out)),
           close(Z)),
       close(In)).

delete_tmp(Tmp) :-
   catch(delete_file(Tmp), _, true).

:- multifile prolog:error_message//1.

prolog:error_message(checksum_error(URL, Expected, Hash)) -->
   [ 'The download of ~w has the SHA-256 ~w, not ~w'-[URL, Hash, Expected] ].
