#!/usr/bin/env node

import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, "..", "..");
const tempRoot = path.join(repoRoot, ".tmp", "workspace-entry-lobster-env-smoke");
const compileRoot = path.join(tempRoot, "compiled");
const sourcePath = path.join(repoRoot, "build", "scripts", "workspace-entry-lobster-env-smoke.ts");
const entryPath = path.join(compileRoot, "build", "scripts", "workspace-entry-lobster-env-smoke.js");
const resultPath = process.argv[2] ? path.resolve(process.argv[2]) : path.join(tempRoot, "result.json");

if (!existsSync(sourcePath)) {
  throw new Error(`Workspace-entry lobster env smoke source was not found: ${sourcePath}`);
}

rmSync(compileRoot, { recursive: true, force: true });
mkdirSync(compileRoot, { recursive: true });

execFileSync("corepack", [
  "pnpm",
  "--dir",
  path.join(repoRoot, "apps", "desktop"),
  "exec",
  "tsc",
  "--module",
  "ES2022",
  "--moduleResolution",
  "node",
  "--target",
  "ES2022",
  "--lib",
  "ES2022",
  "--types",
  "node",
  "--esModuleInterop",
  "--allowSyntheticDefaultImports",
  "--skipLibCheck",
  "--outDir",
  compileRoot,
  sourcePath
], { stdio: "inherit" });

if (!existsSync(entryPath)) {
  throw new Error(`Workspace-entry lobster env smoke entry was not emitted: ${entryPath}`);
}

writeFileSync(path.join(compileRoot, "package.json"), "{\"type\":\"module\"}", "utf8");

execFileSync("node", [entryPath, resultPath], { stdio: "inherit" });

if (!existsSync(resultPath)) {
  throw new Error(`Workspace-entry lobster env smoke did not produce a result file: ${resultPath}`);
}
