#!/usr/bin/env bash

# Traditional vfox PreInstall and PostInstall hooks receive custom tool options
# in ctx.options.

PLUGIN_DIR="$PWD/vfox-structured-options"
MARKER="$PWD/structured-options-marker"

mkdir -p "$PLUGIN_DIR/hooks"

cat >"$PLUGIN_DIR/metadata.lua" <<'LUA'
PLUGIN = {}
PLUGIN.name = "structured-options"
PLUGIN.version = "0.1.0"
PLUGIN.homepage = "https://example.com/structured-options"
PLUGIN.license = "MIT"
PLUGIN.description = "Structured tool options test plugin"
LUA

cat >"$PLUGIN_DIR/hooks/available.lua" <<'LUA'
function PLUGIN:Available(ctx)
	return {
		{ version = "1.0.0" },
	}
end
LUA

cat >"$PLUGIN_DIR/hooks/pre_install.lua" <<'LUA'
local function assert_options(options)
	assert(options.enabled == "true", "expected normalized boolean option")
	assert(options.retries == "3", "expected normalized integer option")
	assert(options.label == "structured", "expected string option")
	assert(options.channels[1] == "stable", "expected first array option")
	assert(options.channels[2] == "beta", "expected second array option")
	assert(options.settings.mode == "strict", "expected nested table option")
end

function PLUGIN:PreInstall(ctx)
	assert_options(ctx.options)
	return {
		version = ctx.version,
	}
end
LUA

cat >"$PLUGIN_DIR/hooks/post_install.lua" <<'LUA'
function PLUGIN:PostInstall(ctx)
	local options = ctx.options
	assert(options.enabled == "true", "expected normalized boolean option")
	assert(options.retries == "3", "expected normalized integer option")
	assert(options.label == "structured", "expected string option")
	assert(options.channels[1] == "stable", "expected first array option")
	assert(options.channels[2] == "beta", "expected second array option")
	assert(options.settings.mode == "strict", "expected nested table option")

	local marker = assert(io.open(options.marker, "w"))
	assert(marker:write("structured"))
	assert(marker:close())
end
LUA

cat >"$PLUGIN_DIR/hooks/env_keys.lua" <<'LUA'
function PLUGIN:EnvKeys(ctx)
	return {}
end
LUA

git -C "$PLUGIN_DIR" init
git -C "$PLUGIN_DIR" add .
git -C "$PLUGIN_DIR" -c user.name="mise" -c user.email="mise@example.com" commit -m "test(vfox): create structured options plugin"

cat >mise.toml <<EOF
[tools]
"vfox:file://$PLUGIN_DIR" = { version = "1.0.0", enabled = true, retries = 3, label = "structured", channels = ["stable", "beta"], settings = { mode = "strict" }, marker = "$MARKER" }
EOF

mise install
assert "cat '$MARKER'" "structured"
