/*
SPDX-FileCopyrightText: 2025–2026 toastal
SPDX-FileCopyrightText: 2026 Nixtamal contributors
SPDX-License-Identifier: ISC

Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
& this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED “AS IS” & ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY & FITNESS. IN
NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
────────────────────────────────────────────────────────────────────────────────
┏┓╻+╻ ╱┏┳┓┏┓┏┳┓┏┓╻
┃┃┃┃┗━┓╹┃╹┣┫┃┃┃┣┫┃   This file was generated by Nixtamal.
╹┗┛╹╱ ╹ ╹ ╹╹╹ ╹╹╹┗┛  Do not edit as it will be overwritten.
────────────────────────────────────────────────────────────────────────────────
*/
{
	system ? null,
	bootstrap-nixpkgs ? null,
	bootstrap-nixpkgs-lock-name ? null,
	bootstrap-pkgs ? null,
}:

let lock = builtins.fromJSON (builtins.readFile (toString ./. + "/lock.json")); in
assert (lock.v == "2.0.0");
let
	isNonemptyString = x: builtins.isString x && x != "";

	isNonemptyList = xs: builtins.isList xs && xs != [ ];

	hash-token = {
		"0" = "sha256";
		"1" = "sha512";
		"2" = "blake3";
	};

	try-fetch = input-name: fetcher:
		let
			try-fetch' = failed-urls: url: urls:
				let result = builtins.tryEval (fetcher url); in
				if result.success then
					result.value
				else
					let failed-urls' = [ url ] ++ failed-urls; in
					if urls == [ ] then
						let fus = builtins.concatStringsSep " " failed-urls'; in
						throw "Input 「${input-name}」fetchable @ [ ${fus} ]"
					else
						try-fetch' failed-urls' (builtins.head urls) (builtins.tail urls);
		in
		try-fetch' [ ];

	builtin-fetch-tarball = { input-name, name, kind, hash }:
		try-fetch input-name (url:
			builtins.fetchTarball ({
				inherit url;
				${hash-token.${builtins.toString hash.al}} = hash.vl;
			}
			// (if isNonemptyString name then { inherit name; } else { }))
		) kind.ur kind.ms;

	builtin-to-input = input-name: input:
		let
			name = input.sn;
			hash = input.ha;
			kind = builtins.elemAt input.kd 1;
			k = builtins.head input.kd;
		in
		if k == 1 then
			builtin-fetch-tarball { inherit input-name name hash kind; }
		else
			throw "Unsupported builtin fetcher “${builtins.toString k}”";

	local-bootstrap-nixpkgs =
		if builtins.isAttrs bootstrap-nixpkgs then
			bootstrap-nixpkgs
		else
			builtin-to-input "bootstrap-nixpkgs-for-nixtamal" (
				if builtins.isString bootstrap-nixpkgs-lock-name then
					if lock.i ? ${bootstrap-nixpkgs-lock-name} then
						lock.i.${bootstrap-nixpkgs-lock-name}
					else
						throw "Input 「${bootstrap-nixpkgs-lock-name}」 missing from the lock.json, so Nixtamal is not bootstrapable; lock if you forgot or look for typos."
				else if lock.i ? nixpkgs-nixtamal then
					lock.i.nixpkgs-nixtamal
				else if lock.i ? nixpkgs then
					lock.i.nixpkgs
				else
					let np = builtins.tryEval <nixpkgs>; in
					if np.success && builtins.isPath np.value then
						builtins.warn
							"Using system-dependent <nixpkgs>; this is more than likely ‘safe’ for Nixtamal’s bootstrapping, but technically not reproducible"
							np.value
					else
						throw (builtins.concatStringsSep "\n" [
							"No Nixtamal bootstrapping Nixpkgs to choose from. Pick from:"
							"❶ Set one of Nixtamal’s import arguments `bootstrap-nixpkgs-lock-name` or `bootstrap-nixpkgs`"
							"❷ Locking an input named `nixpkgs-nixtamal` or `nixpkgs` in the manifest.kdl"
							"❸ Setting $NIX_PATH so `<nixpkgs>` can be used (less reproducible, doesn’t work in pure eval mode)"
						])
			);

	pkgs =
		if builtins.isAttrs bootstrap-pkgs then
			bootstrap-pkgs
		else
			import local-bootstrap-nixpkgs {
				system = if builtins.isString system then system else builtins.currentSystem;
			};

	inherit (pkgs) lib;

	fetch-zip = { input-name, name, kind, hash }:
		pkgs.fetchzip (
			{
				# base gnutar doesn’t support Zstandard
				nativeBuildInputs = [ pkgs.zstd ];
				hash = hash.vl;
			}
			// (if isNonemptyList kind.ms then
					{ urls = [ kind.ur ] ++ kind.ms; }
				else
					{ url = kind.ur; }
				)
			// lib.optionalAttrs (isNonemptyString name) { inherit name; }
			// lib.optionalAttrs (isNonemptyString kind.ex) { extension = kind.ex; }
		);

	to-input = input-name: input:
		let
			name = input.sn;
			hash = input.ha;
			kind = builtins.elemAt input.kd 1;
			k = builtins.head input.kd;
			raw-input =
				if k == 1 then
					let fetch-time = kind.ft; in
					if fetch-time == 0 then
						fetch-zip { inherit input-name name kind hash; }
					else if fetch-time == 1 then
						builtin-fetch-tarball { inherit input-name name kind hash; }
					else
						throw "Unsupported fetch time ${fetch-time}."
				else
					throw "Unsupported input kind “${builtins.toString k}”";
		in
		raw-input;
in
builtins.mapAttrs to-input lock.i
