/** @param {import(".").NS } ns */

export async function main(ns) {
	ns.disableLog('ALL');

	async function writeLog(type, obj) {
		let timeNow = new Date();
		let year = timeNow.getFullYear().toString().substring(2);
		let month = (timeNow.getMonth() < 9 ? '0' : '') + (timeNow.getMonth() + 1);
		let day = (timeNow.getDate() < 10 ? '0' : '') + timeNow.getDate();
		let hour = (timeNow.getHours() < 10 ? '0' : '') + timeNow.getHours();
		let minute = (timeNow.getMinutes() < 10 ? '0' : '') + timeNow.getMinutes();
		let second = (timeNow.getSeconds() < 10 ? '0' : '') + timeNow.getSeconds();
		let timestamp = `${year}${month}${day}_${hour}${minute}${second}`;
		await ns.tryWritePort(1, `t${timestamp}_${type} = ${obj};\n`);

		if (['ERROR', 'TERMINAL'].indexOf(type) != -1) ns.tprint(`${timestamp} ${type} = ${obj}`);
	}

	let server = ns.args[0];
	let maxMoney = ns.getServerMaxMoney(server);
	let minSecurity = ns.getServerMinSecurityLevel(server);
	let loop = 0;
	let previousMoney = 0;

	while (maxMoney != 0) {
		let currentMoney = ns.getServerMoneyAvailable(server);
		let currentSecurity = ns.getServerSecurityLevel(server);

		let hackedMoney = 0;
		if (currentMoney > 0.1 * maxMoney) {
			hackedMoney = await ns.hack(server);
			currentMoney = ns.getServerMoneyAvailable(server);
		}

		if (currentMoney < 0.9 * maxMoney) {
			while (currentMoney <= previousMoney) {
				await ns.grow(server);
				currentMoney = ns.getServerMoneyAvailable(server);
			}
		}
		previousMoney = currentMoney;

		if (currentSecurity > 2 * minSecurity) {
			await ns.weaken(server);
			currentSecurity = ns.getServerSecurityLevel(server);
		}

		ns.print(`{loop: ${++loop}, hack: ${Math.floor(hackedMoney)}, money: ${Math.floor(currentMoney)} / ${Math.floor(maxMoney)} == ${((currentMoney / maxMoney) * 100).toFixed(2)}, security: ${currentSecurity.toFixed(2)} / ${Math.floor(minSecurity)} == ${((currentSecurity / minSecurity) * 100).toFixed(4)}}`);
		await ns.sleep(50);
	}
}