#!/usr/bin/env node

import { execFileSync } from "node:child_process"
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"
import { dirname, join, resolve } from "node:path"

const repoRoot = resolve(import.meta.dirname, "..", "..")
const desktopAppRoot = join(repoRoot, "apps", "desktop")
const sourcePath = join(repoRoot, "build", "scripts", "workspace-startup-smoke.ts")
const tempRoot = join(repoRoot, ".tmp", "workspace-startup-smoke")
const compileRoot = join(tempRoot, "compiled")
const entryPath = join(compileRoot, "build", "scripts", "workspace-startup-smoke.js")
const compilePackagePath = join(compileRoot, "package.json")
const resultPath = resolve(process.argv[2] ?? join(tempRoot, "result.json"))

function writeUtf8File(filePath, content) {
  mkdirSync(dirname(filePath), { recursive: true })
  writeFileSync(filePath, content, "utf8")
}

if (!existsSync(sourcePath)) {
  throw new Error(`Workspace startup smoke source was not found: ${sourcePath}`)
}

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

console.log("Compiling workspace startup smoke with local TypeScript")
execFileSync("corepack", [
  "pnpm",
  "--dir",
  desktopAppRoot,
  "exec",
  "tsc",
  "--module",
  "ES2022",
  "--moduleResolution",
  "node",
  "--target",
  "ES2022",
  "--lib",
  "ES2022",
  "--types",
  "node",
  "--esModuleInterop",
  "--allowSyntheticDefaultImports",
  "--skipLibCheck",
  "--outDir",
  compileRoot,
  sourcePath,
], {
  cwd: repoRoot,
  stdio: "inherit",
})

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

writeUtf8File(compilePackagePath, '{"type":"module"}')

console.log("Running workspace startup smoke")
execFileSync("node", [entryPath, resultPath], {
  cwd: repoRoot,
  stdio: "inherit",
})

if (!existsSync(resultPath)) {
  throw new Error(`Workspace startup smoke did not produce a result file: ${resultPath}`)
}
