/**
 * Failed to minify the file using Terser v5.48.0. Serving the original version.
 * Original file: /npm/ng2ninja@8.0.0/dist/ng2ninja.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
#!/usr/bin/env node
import { parseArgs as b } from "node:util";
import { rimrafSync as g } from "rimraf";
import i from "chalk";
import v from "child_process";
import E from "crypto";
import S from "node:fs";
import k from "node:fs/promises";
import x from "util";
import { glob as O } from "glob";
import f from "prompt";
import w from "axios";
const t = {
	log: console.log,
	error: (e) => console.log(i.red(e)),
	warn: (e) => console.log(i.yellow(e)),
	success: (e) => console.log(i.green(e)),
	debug: (e, r, s) => {
		e.verbose && (s ? console.log(i.gray(r), i.gray(s)) : console.log(i.gray(r)));
	}
}, T = x.promisify(v.exec), u = (e) => k.readFile(e, "utf8"), l = (e) => T(e, { maxBuffer: 1024e3 }), $ = (e) => new Promise((r, s) => {
	f.start(), f.get(e, (o, c) => {
		o ? s(o) : r(c);
	});
}), L = (e) => O(e, {
	nodir: !0,
	posix: !0
}), A = (e) => {
	process.exit(e);
}, C = (e) => {
	const r = S.readFileSync(e), s = E.createHash("sha256");
	return s.update(r), s.digest("hex");
}, F = "coverage/ponyracer/coverage-summary.json", R = {
	covered: 0,
	total: 10
};
function N(e) {
	const r = 100 + e.covered - e.total;
	return r < 0 ? 0 : r;
}
function j(e) {
	const r = e.replace(/\\/g, "/"), s = JSON.parse(r), o = {
		covered: s.total.lines.covered,
		total: s.total.lines.total
	}, c = N(o);
	return c !== 100 ? (t.warn("Code coverage score: " + c + "%"), t.warn("Looks like you don't have a perfect code coverage."), t.warn("Maybe you skipped/deleted some unit tests?"), t.warn("Or maybe you added some code to try something, and this is not covered by a unit test?"), t.warn("To have more info open `coverage/ponyracer/index.html`"), t.warn("You should see which file has a problem.")) : t.success("Code coverage score: 100%"), o;
}
async function J(e) {
	t.log("Starting code coverage...");
	let r;
	try {
		r = await u(F);
	} catch {
		return t.warn("Code coverage score: 0%"), t.warn("No coverage found, probably because some unit tests failed."), R;
	}
	try {
		return j(r);
	} catch (s) {
		throw t.error("Error while reading the code coverage results. Try to run `ng test --watch=false --code-coverage`."), t.debug(e, "Error while reading the code coverage results was: ", s), s;
	}
}
const P = "results/playwright-results.json";
function I() {
	t.error("Error while running end-to-end tests."), t.error("Check if your app is running with no error in the browser console,"), t.error("and try to launch the tests using `ng e2e`.");
}
function U(e) {
	const r = JSON.parse(e), s = r.stats.unexpected, o = r.stats.expected, c = {
		success: o,
		failed: s
	}, n = o + s;
	return n === 0 ? t.error("E2e tests score: 0%") : s ? (t.warn("Looks like you have " + s + " e2e tests failing."), t.warn("Try to launch the tests using `ng e2e`."), t.warn(`E2e tests score: ${Math.round(o * 100 / n)}%`)) : t.success("E2e tests score: 100%"), c;
}
async function _(e) {
	t.log("Starting end to end tests...");
	try {
		await l("ng e2e");
	} catch (r) {
		t.debug(e, "Error while running e2e tests: ", r);
	}
	try {
		return U(await u(P));
	} catch (r) {
		throw t.debug(e, "Error while reading e2e results: ", r), I(), r;
	}
}
function q(e, r) {
	return e.find((s) => s.name.includes(r));
}
function H() {
	return L("./{e2e,src}/**/*.ts");
}
function M(e) {
	return e.map((r) => ({
		name: r,
		hash: C(r)
	}));
}
function V() {
	return H().then((e) => M(e));
}
async function B(e) {
	t.log("Checking submission...");
	let r;
	try {
		r = JSON.parse(await u("./exercise.json"));
	} catch (n) {
		throw t.error("Looks like you have no exercise.json file."), t.debug(e, "An error occurred while reading exercise.json: ", n), new Error("No exercise.json file", { cause: n });
	}
	if (t.success(`Pack V${r.pack} - Exercise ${r.id} - ${r.title}`), e["skip-check"]) return r;
	let s = [];
	try {
		s = await V();
	} catch (n) {
		throw t.debug(e, "Error while computing the hash of the spec files. ", n), n;
	}
	t.debug(e, "Exercise :", JSON.stringify(r)), t.debug(e, "Hashes :", JSON.stringify(s));
	const o = [], c = [];
	if (r.specs.forEach((n) => {
		const h = q(s, n.name);
		h ? h.hash !== n.hash && o.push(n.name) : c.push(n.name);
	}), o.length !== 0 || c.length !== 0) throw o.length !== 0 && (t.error("It looks like you forgot to update these spec files"), t.error("or that you modified them manually:"), o.forEach((n) => t.error(` - ${n}`))), c.length !== 0 && (t.error("It looks like you forgot to add these spec files:"), c.forEach((n) => t.error(` - ${n}`))), t.error("Copy the new specs and try again."), /* @__PURE__ */ new Error("Specs are not up to date");
	return r;
}
const y = "results/lint-results.json";
async function D(e) {
	t.log("Starting code analysis...");
	try {
		await l(`ng lint --format=json --output-file=${y}`);
	} catch {}
	try {
		const r = await u(y), s = JSON.parse(r), o = { errors: 0 };
		if (o.errors = s.map((c) => c.errorCount + c.warningCount).reduce((c, n) => c + n, 0), o.errors !== 0) {
			const c = Math.max(0, 100 - o.errors);
			t.warn("Code quality score: " + c + "%"), t.warn("Looks like you have some issues in your code."), t.warn("Try to run `ng lint` to see what you can fix.");
		} else t.success("Code quality score: 100%");
		return o;
	} catch (r) {
		throw t.error("Error while running `ng lint`."), t.error("Try to run `ng lint`."), t.debug(e, "Error while running lint was: ", r), r;
	}
}
const p = "https://angular-exercises.ninja-squad.com", m = "http://localhost:8080";
function z(e, r) {
	return t.success("Authentication success"), e.token = r, e;
}
async function d(e, r, s) {
	if (r = r + 1, r > 3) return t.error("Aborting authentication after 3 failures"), Promise.reject();
	const o = { properties: {
		email: { required: !0 },
		password: {
			hidden: !0,
			required: !0
		}
	} };
	try {
		const c = await $(o), n = await w.post(`${e["local-server"] ? m : p}/api/authentications`, c);
		return n.status !== 201 ? (t.error("Authentication failed, try again."), t.debug(e, `Authentication request returned with status: ${n.status}`), d(e, r, s)) : (t.debug(e, "Authentication succeeded and we can store credentials"), z(s, n.data.token));
	} catch (c) {
		return t.error("Authentication failed, try again."), t.debug(e, "An error occurred during authentication: ", c), d(e, r, s);
	}
}
function G(e, r) {
	const s = e.e2e.success + e.e2e.failed === 0 ? 25 : e.e2e.failed;
	let o = 100 - e.vitest.failed * 5 - e.lint.errors - (e.coverage.total - e.coverage.covered) - s;
	return o < 10 && (o = 10), r.local ? (o !== 100 && (t.error("Score is not perfect! " + o + "%"), A(1)), t.success("Exercise score: " + o + "%")) : o !== 100 ? t.warn("Score is not perfect yet: " + o + "%") : t.success("Perfect score, congrats! " + o + "%"), o;
}
async function W(e, r) {
	const s = { Authorization: `Bearer: ${r.token}` }, o = e["local-server"] ? m : p, c = { score: r.score };
	try {
		const n = await w.post(`${o}/api/packs/${r.pack}/exercises/${r.id}/scores`, c, { headers: s });
		return n.status !== 201 ? (t.error("Error while sending the results."), t.debug(e, `${n.status}`, JSON.stringify(n.data)), Promise.reject()) : (t.log("Score submitted."), r);
	} catch (n) {
		throw t.error("Error while sending the results."), t.error("Maybe check your connection?"), t.debug(e, "Error while sending the result was: ", n), n;
	}
}
async function Y(e, r) {
	let s;
	try {
		s = JSON.parse(await u("./exercise.json"));
	} catch (o) {
		throw t.error("Looks like you have no exercise.json file."), t.debug(r, "An error occurred while reading exercise.json: ", o), o;
	}
	return s.score = G(e, r), r.local ? s : W(r, await d(r, 0, s));
}
const K = "results/vitest-results.json";
function Q(e) {
	if (e.failed === void 0 || e.success === 0) return 0;
	const r = 100 - e.failed * 5;
	return r >= 0 ? r : 0;
}
function X(e) {
	const r = Q(e);
	t.warn("Unit tests score: " + r + "%"), t.warn("Looks like you have " + (e.failed ? e.failed : "a few") + " unit test(s) failing."), t.warn("Run `ng test` and try to fix them.");
}
function Z() {
	t.error("Error while running unit tests."), t.error("Maybe your code doesn't compile?"), t.error("Run `ng test` to see more.");
}
function ee(e) {
	const r = JSON.parse(e);
	if (!r) throw t.error("An error occurred during the unit tests."), t.error("Run `ng test` to see the problem."), /* @__PURE__ */ new Error("Invalid test results");
	const s = {
		failed: r.numFailedTests ? r.numFailedTests : r.numFailedTestSuites,
		success: r.numPassedTests
	};
	return s.failed !== 0 || s.success === 0 ? X(s) : t.success("Unit tests score: 100%"), s;
}
async function re(e) {
	t.log("Starting unit tests...");
	try {
		await l("ng test --no-watch --coverage");
	} catch (r) {
		t.debug(e, "Unit test failed", r);
	}
	try {
		return ee(await u(K));
	} catch (r) {
		throw t.debug(e, "An error occurred while reading vitest results: ", r), Z(), r;
	}
}
const te = process.argv.slice(2), { values: a } = b({
	args: te,
	parseArgsOptions: {
		local: { type: "boolean" },
		"local-server": { type: "boolean" },
		verbose: { type: "boolean" },
		"skip-check": { type: "boolean" }
	},
	strict: !1
});
g("results"), g("coverage");
try {
	const e = await B(a);
	t.debug(a, "Exercise: ", e.title);
	const r = await re(a);
	t.debug(a, "Vitest results: ", JSON.stringify(r));
	const s = await J(a);
	t.debug(a, "Coverage results: ", JSON.stringify(s));
	const o = await D(a);
	t.debug(a, "Linter results: ", JSON.stringify(o));
	const c = await _(a);
	t.debug(a, "E2e results: ", JSON.stringify(c)), await Y({
		exercise: e,
		vitest: r,
		coverage: s,
		lint: o,
		e2e: c
	}, a);
} catch (e) {
	t.error("Try to fix it and retry!"), a.verbose && t.error(e), a.local && (t.error("Running locally, we exit"), process.exit(1));
}
