/** What opening something in the default application needs from the machine; tests pass their own. */
export type OpenEnvironment = {
  platform: NodeJS.Platform
  env: Record<string, string | undefined>
  start: (command: string, args: string[]) => void
}

const OPENERS: Partial<Record<NodeJS.Platform, (target: string) => string[]>> = {
  darwin: (target) => ['open', target],
  linux: (target) => ['xdg-open', target],
  /** Not `cmd /c start`: cmd reads `&`, `|`, `%` and `^` in the target as its own syntax; rundll32 takes it as one argument. */
  win32: (target) => ['rundll32', 'url.dll,FileProtocolHandler', target],
}

/** The command and arguments that open a file or a link in the default application of the platform, null when there is none. */
export const openCommandFor = (platform: NodeJS.Platform, target: string): string[] | null =>
  OPENERS[platform]?.(target) ?? null

/** Linux opens things in a graphical session only; elsewhere the platform's opener is assumed to work. */
export const hasDisplay = ({ platform, env }: Pick<OpenEnvironment, 'platform' | 'env'>): boolean =>
  platform !== 'linux' || Boolean(env.DISPLAY || env.WAYLAND_DISPLAY)

const systemEnvironment = (): OpenEnvironment => ({
  platform: process.platform,
  env: process.env,
  start: (command, args) => {
    Bun.spawn([command, ...args], { stdout: 'ignore', stderr: 'ignore' })
  },
})

/**
 * Opens a file or a link in the default application. Returns the reason when that was not possible (no
 * opener for the platform, no display, the opener could not be started), null when it was started.
 */
export const openInBrowser = (target: string, environment: OpenEnvironment = systemEnvironment()): string | null => {
  const command = openCommandFor(environment.platform, target)
  if (!command) return `no way to open ${target} on ${environment.platform}`
  if (!hasDisplay(environment)) return 'no display'
  const [opener, ...args] = command
  try {
    environment.start(opener, args)
    return null
  } catch (error) {
    return `${opener} ${target}: ${error instanceof Error ? error.message : String(error)}`
  }
}
