import { type ChildProcess, spawn } from 'node:child_process'
import { watch } from 'node:fs'
import { dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { TERMINAL_OFF } from '../terminal/lifetime'
import { pendingKitUpdate, VERSION_POLL_MS } from '../version/installed-version'
import type { StartedKit } from '../version/started-kit'
import { STOP_REQUEST, type Stopper, stopperOf } from './child-stop'
import { HERD_COMMAND } from './herd-command'
import { CHILD_MARKER, exitCodeOf, isRestartTrigger, nextStep, RESTART_DEBOUNCE_MS } from './restart-decision'

const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const

const packageSourceDirectory = (): string => dirname(dirname(fileURLToPath(import.meta.url)))

const entryScript = (): string => {
  const script = process.argv[1]
  if (!script) throw new Error('Cannot supervise the herd: process.argv[1] is missing')
  return script
}

const describeEnd = (code: number | null, signal: NodeJS.Signals | null): string =>
  signal ? `signal ${signal}` : `exit ${code}`

const spawnView = (scriptPath: string, args: string[]): ChildProcess =>
  spawn(process.execPath, [scriptPath, HERD_COMMAND.name, ...args], {
    stdio: 'inherit',
    env: { ...process.env, [CHILD_MARKER]: '1' },
  })

/**
 * Runs the live view as a child process and restarts it when the package's own source changes,
 * so a long-lived `plans` never shows the behaviour of code that has since been edited. The child
 * stops on SIGTERM through the handler that restores the terminal, and is killed when it does not end within
 * `GRACE_MS` (a restart included); a second signal while stopping kills it at once. Resolves with the exit code
 * of a wanted end only: the child's clean exit (`q`) or a signal forwarded to it. A child that
 * dies otherwise leaves the supervisor waiting, with the terminal restored, for the next change
 * to `src/`, which spawns a fresh child. `kit` is the package this process loaded (null when it cannot be
 * located, which turns the version check off). A failure to spawn the very first child resolves with 1.
 *
 * Meant to run once per process: the signal listeners it registers stay registered.
 */
export const superviseView = (
  args: string[],
  kit: StartedKit | null,
  scriptPath: string = entryScript(),
): Promise<number> =>
  new Promise((resolveExit) => {
    let child: ChildProcess | undefined
    let stopper: Stopper | undefined
    let restarting = false
    let stopping = false
    let timer: ReturnType<typeof setTimeout> | undefined
    let runningKit = kit

    const finish = (code: number): void => {
      clearTimeout(timer)
      clearInterval(versionTimer)
      watcher.close()
      resolveExit(code)
    }

    const waitForChange = (reason: string): void => {
      child = undefined
      process.stdout.write(TERMINAL_OFF)
      console.log(`herd stopped (${reason}); waiting for the next change to src/`)
    }

    const start = (isFirst: boolean): void => {
      const current = spawnView(scriptPath, args)
      child = current
      const currentStopper = stopperOf({
        kill: (signal) => current.kill(signal),
        setTimer: (run, ms) => setTimeout(run, ms),
        clearTimer: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
      })
      stopper = currentStopper

      current.on('error', (error) => {
        if (child !== current) return
        if (isFirst) {
          console.error(`herd could not start: ${error.message}`)
          finish(1)
          return
        }
        console.error(error.message)
        waitForChange('error')
      })

      current.on('exit', (code, signal) => {
        currentStopper.ended()
        if (child !== current) return
        const context = { restarting, stopping, code, signal }
        restarting = false
        const actions = {
          respawn: () => start(false),
          exit: () => finish(exitCodeOf(code, signal)),
          wait: () => waitForChange(describeEnd(code, signal)),
        }
        actions[nextStep(context)]()
      })
    }

    const restartView = (): void => {
      if (child) {
        restarting = true
        stopper?.request('SIGTERM')
      } else start(false)
    }

    const watcher = watch(packageSourceDirectory(), { recursive: true }, (_event, name) => {
      if (stopping || !name || !isRestartTrigger(name.toString())) return
      clearTimeout(timer)
      timer = setTimeout(restartView, RESTART_DEBOUNCE_MS)
    })

    const versionTimer = setInterval(() => {
      const update = pendingKitUpdate(runningKit)
      if (stopping || !update || !runningKit) return
      runningKit = { ...runningKit, version: update.to }
      restartView()
    }, VERSION_POLL_MS)

    start(true)

    for (const signal of FORWARDED_SIGNALS) {
      process.on(signal, () => {
        stopping = true
        clearTimeout(timer)
        clearInterval(versionTimer)
        if (!child || !stopper) finish(exitCodeOf(null, signal))
        else if (stopper.request(signal) === STOP_REQUEST.killed) finish(exitCodeOf(null, signal))
      })
    }
  })
