#!/usr/bin/env node
/**
 * Fix remaining node:test API calls that the initial migration missed.
 *
 * 1. t.after(() => ...) → afterEach(() => ...)  (add afterEach to imports if needed)
 * 2. t.before(() => ...) → beforeEach(() => ...) (add beforeEach to imports if needed)
 * 3. await t.test("name", fn) → test("name", fn) (flatten subtests)
 * 4. t.skip("msg") → return ctx.skip("msg") — only in describe blocks; most are top-level test() calls
 *    where t.skip() should become a return or conditional.
 */

import { readFileSync, writeFileSync } from "node:fs";
import { execSync } from "node:child_process";

const files = execSync(
	'grep -rl "t\\.after\\b\\|t\\.before\\b\\|t\\.test(\\|t\\.skip(" src/tests/ src/resources/extensions/ --include="*.test.ts" --include="*.test.mjs"',
	{ encoding: "utf-8", maxBuffer: 50 * 1024 * 1024 },
)
	.trim()
	.split("\n")
	.filter(Boolean);

console.log(`Fixing ${files.length} files`);

let updated = 0;

for (const file of files) {
	let content = readFileSync(file, "utf-8");
	let changed = false;

	// 1. t.after(() => ...) → afterEach(() => ...)
	if (content.includes("t.after(")) {
		content = content.replace(/\bt\.after\(/g, "afterEach(");
		changed = true;
	}

	// 2. t.before(() => ...) → beforeEach(() => ...)
	if (content.includes("t.before(")) {
		content = content.replace(/\bt\.before\(/g, "beforeEach(");
		changed = true;
	}

	// 3. await t.test("name", fn) → test("name", fn)
	//    and t.test("name", fn) without await
	if (content.includes("t.test(")) {
		content = content.replace(/await\s+t\.test\(/g, "test(");
		content = content.replace(/\bt\.test\(/g, "test(");
		changed = true;
	}

	// 4. t.skip("msg") → remove or comment — these are rare (4 files)
	//    In most cases t.skip is inside a test callback and means "skip this test".
	//    Vitest uses test.skip() at declaration time, not runtime.
	//    Best effort: replace with return + comment
	if (content.includes("t.skip(")) {
		content = content.replace(/\bt\.skip\(([^)]*)\)/g, 'return; // skip: $1');
		changed = true;
	}

	// 5. Ensure afterEach/beforeEach are imported from vitest if used
	if (changed) {
		const needsAfterEach = content.includes("afterEach(");
		const needsBeforeEach = content.includes("beforeEach(");

		if (needsAfterEach || needsBeforeEach) {
			// Find the vitest import line and extend it
			const vitestImportMatch = content.match(/import\s+\{([^}]+)\}\s+from\s+['"]vitest['"];?/);
			if (vitestImportMatch) {
				const existing = vitestImportMatch[1].split(",").map((s) => s.trim());
				const additions = [];
				if (needsAfterEach && !existing.includes("afterEach")) additions.push("afterEach");
				if (needsBeforeEach && !existing.includes("beforeEach")) additions.push("beforeEach");

				if (additions.length > 0) {
					const all = [...existing, ...additions];
					const newImport = `import { ${all.join(", ")} } from 'vitest';`;
					content = content.replace(vitestImportMatch[0], newImport);
				}
			}
		}
	}

	if (changed) {
		writeFileSync(file, content, "utf-8");
		updated++;
	}
}

console.log(`Updated ${updated} files`);
