import { existsSync } from 'node:fs'
import { fetchBase, fetchPlanHeads } from '../plans/fetch'
import { commitOf } from '../plans/git'
import { BASE_REMOTE, baseRefOf } from '../plans/settings'
import { baseFetchNeeded, movedHeads, remoteTipOf } from './base-tip'
import { behindCountOf, type MainCheckoutRead } from './main-checkout'
import type { WatchedPullRequest } from './pull-requests'

const GIT_ASYNC_TIMEOUT_MS = 30_000

/** Runs git without blocking, killed after the timeout; its stdout, or null when it failed. Never rejects. */
const gitAsync = async (cwd: string, args: string[]): Promise<string | null> => {
  try {
    const child = Bun.spawn(['git', '-C', cwd, ...args], {
      stdout: 'pipe',
      stderr: 'ignore',
      env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
    })
    const timer = setTimeout(() => child.kill(), GIT_ASYNC_TIMEOUT_MS)
    const [stdout, exitCode] = await Promise.all([new Response(child.stdout).text(), child.exited])
    clearTimeout(timer)
    return exitCode === 0 ? stdout : null
  } catch {
    return null
  }
}

const git = (cwd: string, args: string[]): string | null => {
  const result = Bun.spawnSync(['git', '-C', cwd, ...args], { stdout: 'pipe', stderr: 'pipe' })
  return result.exitCode === 0 ? result.stdout.toString().trim() : null
}

/** The branch checked out in a worktree, or null for a missing worktree or a detached head. */
export const branchOf = (worktree: string): string | null =>
  existsSync(worktree) ? git(worktree, ['branch', '--show-current']) || null : null

/**
 * The main checkout's branch and the commits of `origin/<base>` it lacks, as far as git can tell; read from local refs
 * only. Null when git cannot resolve HEAD, so an unreadable checkout never reads as a detached head.
 */
export const readMainCheckout = (root: string, baseBranch: string): MainCheckoutRead | null => {
  if (git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']) === null) return null
  const remoteBase = baseRefOf({ baseBranch })
  return {
    branch: branchOf(root),
    behind: behindCountOf(git(root, ['rev-list', '--count', `HEAD..${remoteBase}`])),
    remoteBase,
  }
}

/**
 * Fetches the base branch when the remote moved past `origin/<branch>`, so every reader of that ref
 * (the herd watches `FETCH_HEAD`) sees a merge as soon as the watcher does. Asks the remote
 * first, so an unchanged base costs no fetch; a failure leaves the ref as it is.
 */
export const fetchBaseWhenMoved = async (root: string, branch: string): Promise<void> => {
  const [remote, local] = await Promise.all([
    gitAsync(root, ['ls-remote', BASE_REMOTE, `refs/heads/${branch}`]),
    gitAsync(root, ['rev-parse', '--verify', '--quiet', `${BASE_REMOTE}/${branch}^{commit}`]),
  ])
  if (!baseFetchNeeded(remote === null ? null : remoteTipOf(remote, branch), local?.trim() || null)) return
  await fetchBase(root, BASE_REMOTE, branch)
}

/**
 * Fetches the heads of the plan pull requests whose head commit moved past the herd's ref of it, in one call, so the
 * watcher and the herd read the same ticks; an unchanged head costs no fetch, a failure leaves the refs as they are.
 */
export const fetchPlanHeadsWhenMoved = (root: string, pullRequests: readonly WatchedPullRequest[]): Promise<void> =>
  fetchPlanHeads(
    root,
    BASE_REMOTE,
    movedHeads(pullRequests, (ref) => commitOf(root, ref)),
  )
