#!/usr/bin/env node

import { spawn, spawnSync } from "node:child_process";
import { resolve } from "node:path";

const __dirname = import.meta.dirname;
const root = resolve(__dirname, "..");
const sourceBinPath = resolve(root, "bin", "sf-from-source");
const ensureResourcesPath = resolve(
	root,
	"scripts",
	"ensure-source-resources.cjs",
);
const srcLoaderPath = resolve(root, "src", "loader.ts");
const resolveTsPath = resolve(
	root,
	"src",
	"resources",
	"extensions",
	"sf",
	"tests",
	"resolve-ts.mjs",
);

const resourceBuild = spawnSync(process.execPath, [ensureResourcesPath], {
	cwd: root,
	stdio: "inherit",
	env: process.env,
});

if (resourceBuild.status !== 0) {
	process.exit(resourceBuild.status ?? 1);
}

const child = spawn(
	process.execPath,
	[
		"--import",
		resolveTsPath,
		"--experimental-strip-types",
		srcLoaderPath,
		...process.argv.slice(2),
	],
	{
		cwd: process.cwd(),
		stdio: "inherit",
		env: {
			...process.env,
			SF_BIN_PATH: process.env.SF_BIN_PATH || sourceBinPath,
			SF_CLI_PATH: process.env.SF_CLI_PATH || sourceBinPath,
		},
	},
);

child.on("error", (error) => {
	console.error(
		`[forge] Failed to launch local dev CLI: ${error instanceof Error ? error.message : String(error)}`,
	);
	process.exit(1);
});

child.on("exit", (code, signal) => {
	if (signal) {
		process.kill(process.pid, signal);
		return;
	}
	process.exit(code ?? 0);
});
