import { spawnSync } from 'node:child_process'

/** What a run of an external program answered; `missing` is true when there is no such program to run at all. */
export type ToolRun = { exitCode: number; output: string; missing: boolean }

/** Runs one external program with arguments, never through a shell. */
export type RunTool = (binary: string, args: string[]) => ToolRun

/**
 * The external programs the kit works with, as far as they are installed; `herdrInstallable` is true where the
 * official herdr installer applies (Linux and macOS).
 */
export type ToolPresence = { herdr: boolean; gh: boolean; herdrInstallable: boolean }

type Environment = Record<string, string | undefined>

/**
 * The installers the kit may run after a yes: each tool's official script, HTTPS-only on every redirect. The script
 * is downloaded whole into a temporary file before `sh` runs it, so a download cut off midway runs nothing and a
 * failed download ends with curl's exit code. Wrapped in `sh -c`, the command is also safe to paste into any
 * interactive shell: its `exit` ends only the inner shell. herdr's applies to Linux and macOS.
 */
export const INSTALLERS = {
  herdr:
    'sh -c \'installer=$(mktemp) && curl --proto =https --tlsv1.2 -fsSL https://herdr.dev/install.sh -o "$installer" && sh "$installer"; code=$?; rm -f "$installer"; exit $code\'',
} as const

export type InstallerName = keyof typeof INSTALLERS

/** The binary herdr names in `HERDR_BIN_PATH`, else `herdr` from the PATH. */
export const herdrBinary = (env: Environment): string => env.HERDR_BIN_PATH || 'herdr'

const INSTALLABLE_PLATFORMS: readonly NodeJS.Platform[] = ['linux', 'darwin']

const isPresent = (run: RunTool, binary: string): boolean => !run(binary, ['--version']).missing

/** Which tools are installed, asked by running them; a program that runs at all counts, whatever it answers. */
export const detectTools = (env: Environment, platform: NodeJS.Platform, run: RunTool): ToolPresence => ({
  herdr: isPresent(run, herdrBinary(env)),
  gh: isPresent(run, 'gh'),
  herdrInstallable: INSTALLABLE_PLATFORMS.includes(platform),
})

/** `env` is passed on because Bun looks the binary up in it. */
export const spawnTool =
  (env: Environment): RunTool =>
  (binary, args) => {
    const result = spawnSync(binary, args, { encoding: 'utf-8', env })
    const output = `${result.error?.message ?? ''} ${result.stdout ?? ''}${result.stderr ?? ''}`.trim()
    const missing = (result.error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'
    return { exitCode: result.status ?? 1, output, missing }
  }
