from test/more import *;

requires_capability( "fs" );

from std/data/json import JSON;
from std/digest/sha import sha256_hex;
from std/io import Path;
from std/zuzuzoo import Zuzuzoo;

function ensure_dir ( path ) {
	return true if path.exists();
	let parent := path.parent();
	ensure_dir(parent) if not parent.exists();
	path.mkdir();
	return true;
}

function root () {
	let dir := Path.tempdir();
	let lib := dir.child("lib");
	let bin := dir.child("bin");
	let meta := dir.child("meta");
	ensure_dir(lib);
	ensure_dir(bin);
	ensure_dir(meta);
	return {
		dir_obj: dir,
		lib_obj: lib,
		bin_obj: bin,
		meta_obj: meta,
		lib_dir: lib.to_String(),
		bin_dir: bin.to_String(),
		meta_dir: meta.to_String(),
	};
}

function script_entry ( root, install_as, text ) {
	let path := root{bin_obj}.child(install_as);
	path.spew_utf8(text);
	return {
		source: "scripts/" _ install_as,
		install_as: install_as,
		sha256: sha256_hex(path.slurp()),
		wrappers: [],
	};
}

function module_entry ( root, install_as, text ) {
	let dir := root{lib_obj}.child("dist");
	ensure_dir(dir);
	let path := dir.child("mod.zzm");
	path.spew_utf8(text);
	return {
		source: "modules/" _ install_as,
		install_as: install_as,
		sha256: sha256_hex(path.slurp()),
	};
}

function write_installed ( root, name, version, modules, scripts ) {
	( new JSON( pretty: true ) ).dump(
		root{meta_obj}.child( name _ "-" _ version _ ".json" ),
		{
			name: name,
			version: version,
			author: "Example",
			license: "MIT",
			status: "stable",
			dependencies: {},
			installed: {
				zdf: "ZDF-1",
				lib_dir: root{lib_dir},
				bin_dir: root{bin_dir},
				meta_dir: root{meta_dir},
				modules: modules,
				scripts: scripts,
			},
		},
	);
}

let target := root();
write_installed(
	target,
	"script-only",
	"1.0.0",
	[],
	[ script_entry( target, "script-only.zzs", "say \"script\";\n" ) ],
);
write_installed(
	target,
	"module-dist",
	"1.0.0",
	[ module_entry( target, "dist/mod.zzm", "// mod\n" ) ],
	[],
);

let zoo := new Zuzuzoo(
	lib_dir: target{lib_dir},
	bin_dir: target{bin_dir},
	meta_dir: target{meta_dir},
	home: Path.tempdir().to_String(),
);

let by_option := zoo.verify( "script-only", { dist: true } );
ok( by_option{ok}, "verify supports dist option for script-only installs" );
is( by_option{distributions}[0]{name}, "script-only", "dist option uses distribution name" );

let mixed := zoo.verify(
	[
		{ type: "dist", value: "script-only" },
		{ type: "module", value: "dist/mod" },
		{ type: "distribution", value: "script-only" },
	],
);
ok( mixed{ok}, "verify supports mixed target records" );
is( mixed{distributions}.length(), 2, "duplicate distribution targets are de-duped" );
is( mixed{skipped_duplicates}.length(), 1, "duplicate target is reported" );

done_testing();
