local function get_ipkg_executable(ipkg_path)
	local file = io.open(ipkg_path)

	if file == nil then
		return nil
	end

	for line in file:lines() do
		local _, start = line:find("executable%s*=%s*\"")

		if start ~= nil then
			file:close()
			return line:sub(start + 1, #line - 1)
		end
	end

	file:close()
	return nil
end

local function setup_tasks()
	local overseer = require("overseer")

	local generic_build_tmpl =  {
		name = "Idris2 Generic Build",
		params = {
			ipkg_path = { type = "string", optional = false, default = "./main.ipkg" },
		},
		builder = function(params)
			return {
				name = "Idris2: Build " .. params.ipkg_path,
				cmd = { 'idris2', '--build', params.ipkg_path },
				components = {
					{ "on_exit_set_status", success_codes = { 0 } },
				},
			}
		end,
	}

	overseer.register_template(generic_build_tmpl)

	local generic_run_tmpl = {
		name = "Idris2 Generic Run",
		params = {
			ipkg_path = { type = "string", optional = false, default = "./main.ipkg" },
		},
		builder = function(params)
			local executable_name = get_ipkg_executable(params.ipkg_path)

			if params.ipkg_path == nil then
				return nil
			end

			return {
				name = "Idris2: Run " .. params.ipkg_path,
				cmd = { './build/exec/' .. executable_name },
				components = {
					{
						"dependencies",
						task_names = {
							{ "Idris2 Generic Build", ipkg_path = params.ipkg_path },
						},
						sequential = true,
					},
					{ "on_exit_set_status", success_codes = { 0 } },
				},
			}
		end,
	}

	overseer.register_template(generic_run_tmpl)

	overseer.register_template {
		name = "Idris2 compilation",
		generator = function(_, cb)
			local ipkg_paths = require('plenary.scandir').scan_dir(
				'.', { search_pattern = '.+[.]ipkg$', }
			)

			local templates = {}

			for _, ipkg_path in pairs(ipkg_paths) do
				table.insert(
					templates,
					overseer.wrap_template(
						generic_build_tmpl,
						{ name = "Build " .. ipkg_path},
						{ ipkg_path = ipkg_path }
					)
				)

				table.insert(
					templates,
					overseer.wrap_template(
						generic_run_tmpl,
						{ name = "Run " .. ipkg_path },
						{ ipkg_path = ipkg_path }
					)
				)
			end

			cb(templates)
		end,
	}
end

return {
	"ShinKage/idris2-nvim",
	requires = {
		'neovim/nvim-lspconfig',
		'MunifTanjim/nui.nvim',
		'stevearc/overseer.nvim',
		'nvim-lua/plenary.nvim',
	},
	ft = { 'idris2', 'ipkg' },
	cond = function()
		return vim.fn.executable("idris2") ~= 0
			and vim.fn.executable("idris2-lsp") ~= 0
	end,
	opts = {
		autostart_semantic = true,
	},
	config = function(_, opts)
		setup_tasks()

		require("idris2").setup(opts)
	end,
}