local lib = starlit.mod.lib
local scenario = starlit.world.scenario
local log = starlit.logger 'scenario'

local function makeChip(label, schem, sw)
	local E = starlit.mod.electronics
	local files = {}
	local sz = 0
	for _, e in ipairs(schem) do
		local p = E.sw.findSchematicFor(e[1])
		if p then
			local file = {
				kind = 'sw', name = '', drm = e[2];
				body = {pgmId = p, conf = {}};
			}
			table.insert(files, file)
			sz = sz + E.chip.fileSize(file)
		end
	end
	for _, e in ipairs(sw) do
		local file = {
			kind = 'sw', name = '', drm = e[2];
			body = {pgmId = e[1], conf = {}};
		}
		table.insert(files, file)
		sz = sz + E.chip.fileSize(file)
	end
	local chip = ItemStack(assert(E.chip.findBest(function(c)
		return c.flash >= sz, c.ram + c.clockRate
	end)))
	local r = E.chip.read(chip)
	r.label = label
	r.files = files
	E.chip.write(chip, r)
	return chip
end

local chipLibrary = {
	compendium = makeChip('The Gentleman Adventurer\'s Compleat Wilderness Compendium', {
		{'starlit_electronics:battery_chemical_imperial_small', 0};
	}, {
		{'starlit_electronics:shred', 0};
		--{'starlit_electronics:compile_empire', 0};
		{'starlit_electronics:autodoc_deluxe', 1};
		--{'starlit_electronics:driver_compiler_empire', 0};
	});
	survivalware = makeChip('Emergency Survivalware', {
		{'starlit_electronics:battery_chemical_commune_small', 0};
	}, {
		{'starlit_electronics:shred', 0};
		{'starlit_electronics:compile_commune', 0};
		{'starlit_electronics:nanomed', 0};
		{'starlit_electronics:driver_compiler_commune', 0};
	});
	misfortune = makeChip("Sold1er0fMisf0rtune TOP Schematic Crackz REPACK", {
		{'starlit_electronics:battery_chemical_usukwinya_mid', 0};
		{'starlit_electronics:battery_hybrid_imperial_small', 0};
		-- ammunition
	}, {});
}

local battery = function(name)
	local s = ItemStack(name)
	starlit.mod.electronics.battery.setChargeF(s, 1.0)
	return s
end

local function volume(kind,name,mass)
	local sorted = {}
	for k,v in pairs(starlit.item.canister.db) do
		table.insert(sorted, {id=k, can=v})
	end
	table.sort(sorted, function(a,b) return a.can.vol < b.can.vol end)

	local liq = starlit.world.material[kind].db[name]

	local can
	for i, v in ipairs(sorted) do
		if v.can.vol <= liq.density * mass then
			can = ItemStack(i)
			break
		end
	end
	if can == nil then log.fatal('failed to find canister size for gift %s', kind) end

	local st = starlit.item.canister.meta(can)
	st.write('contents', {kind = kind, id = name, mass = mass})

	return can
end


table.insert(scenario, {
	id = 'starlit_scenario:imperialExpat';
	name = 'Imperial Expat';
	desc = "Hoping to escape a miserable life deep in the grinding gears of the capitalist machine for the bracing freedom of the frontier, you sought entry as a colonist to the new Commune world of Thousand Petal. Fate -- which is to say, terrorists -- intervened, and you wound up stranded on Farthest Shadow with little more than the nanosuit on your back, ship blown to tatters and your soul thoroughly mauled by the explosion of a twisted alien artifact -- which SOMEONE neglected to inform you your ride would be carrying.\nAt least you got some nifty psionic powers out of this whole clusterfuck. Hopefully they're safe to use.";

	species = 'human';
	speciesVariant = 'female';
	soul = {
		externalChannel = true; -- able to touch other souls in the spiritual realm
		physicalChannel = true; -- able to extend influence into physical realm
		damage = 1;
	};
	social = {
		empire = 'workingClass';
		commune = 'metic';
	};

	startingItems = {
		suit = ItemStack('starlit_suit:suit_survival_commune');
		suitBatteries = {battery 'starlit_electronics:battery_carbon_commune_small'};
		suitChips = {
			chipLibrary.survivalware;
			-- you didn't notice it earlier, but your Commune environment suit
			-- came with this chip already plugged in. it's apparently true
			-- what they say: the Commune is always prepared for everything.
			-- E V E R Y T H I N G.
		};
		suitGuns = {};
		suitAmmo = {};
		suitCans = {
-- 			ItemStack('starlit_material:canister_small');
			volume('liquid', 'water', 5);
		};
		carry = {
			chipLibrary.compendium;
			-- you bought this on a whim before you left the Empire, and
			-- just happened to still have it on your person when everything
			-- went straight to the Wild Gods' privy
		};
	};
})

table.insert(scenario, {
	id = 'starlit_scenario:gentlemanAdventurer';
	--       Othar Tryggvasson,
	name = 'Gentleman Adventurer';
	desc = "Tired of the same-old-same-old, sick of your idiot contemporaries, exasperated with the shallow soul-rotting luxury of life as landless lordling, and earnestly eager to enrage your father, you resolved to see the Reach in all her splendor. Deftly evading the usual tourist traps, you finagled your way into the confidence of the Commune ambassador with a few modest infusions of Father's money -- now *that* should pop his monocle -- and secured yourself a seat on a ride to their brand-new colony at Thousand Petal. How exciting -- a genuine frontier outing!";

	species = 'human';
	speciesVariant = 'male';
	soul = {
		externalChannel = true;
		physicalChannel = true;
		damage = 1;
	};
	social = {
		empire = 'aristo';
	};

	startingItems = {
		suit = 'starlit_suit:suit_survival_imperial';
		suitBatteries = {battery 'starlit_electronics:battery_supercapacitor_imperial_mid'};
		suitChips = {
			chipLibrary.compendium;
			-- Mother, bless her soul, simply insisted on buying you this as a parting
			-- gift. "it's dangerous out there for a young man," she proclaimed as
			-- if she had profound firsthand experience of the matter. mindful of the
			-- husband she endures, you suffered to humor her, and made a big show of
			-- installing it your brand-new nanosuit before you fled the family seat.
		};
		suitGuns = {};
		suitAmmo = {};
		suitCans = {
			ItemStack('starlit_material:canister_mid');
		};
		carry = {};
	};
})

table.insert(scenario, {
	-- you start out with strong combat abilities but weak engineering,
	-- and will have to scavenge wrecks to find basic crafting gear
	id = 'starlit_scenario:terroristTagalong';
	name = 'Terrorist Tagalong';
	desc = "It turns out there's a *reason* Crown jobs pay so well.";
	species = 'human';
	speciesVariant = 'female';
	social = {
		empire = 'lowlife';
		commune = 'mostWanted';
		underworldConnections = true;
	};
	soul = {
		externalChannel = true;
		physicalChannel = true;
		damage = 2; -- closer to the blast
	};
	startingItems = {
		suit = 'starlit_suit:suit_combat_imperial';
		suitBatteries = {
			ItemStack('starlit_electronics:battery_supercapacitor_imperial_small');
			ItemStack('starlit_electronics:battery_chemical_imperial_large');
		};
		suitGuns = {};
		suitAmmo = {};
		carry = {};
	};
	suitChips = {chipLibrary.misfortune};
})

table.insert(scenario, {
	id = 'starlit_scenario:tradebirdBodyguard';
	name = 'Tradebird Bodyguard';
	desc = "You've never understood why astropaths of all people *insist* on bodyguards. This one could probably make hash of a good-sized human batallion, if her feathers were sufficiently ruffled. Perhaps it's a status thing. Whatever the case, it's easy money.\nAt least, it was supposed to be.'";
	species = 'usukwinya';
	speciesVariant = 'male';
	soul = {
		damage = 0; -- Inyukiriku and her entourage fled the ship when she sensed something serious was about to go down. lucky: the humans only survived because their souls were closed off to the Physical. less luckily, the explosion knocked your escape pod off course and the damn astropath was too busy saving her own skin to come after you
		externalChannel = true; -- usukwinya are already psionic
		physicalChannel = true; -- usukwinya are Starlit
	};
	startingItems = {
		suit = 'starlit_suit:suit_combat_usukwinya';
		suitBatteries = {
			ItemStack('starlit_electronics:battery_hybrid_usukwinya_mid');
		};
		suitGuns = {};
		suitChips = {};
		suitAmmo = {};
		carry = {};
	};
})
