import { existsSync, readdirSync, statSync } from 'node:fs'
import { dirname } from 'node:path'
import { createProcessSlots } from './process-slots'
import type { BaseRefInfo } from './sprint-page'
import type { BranchStatus, WorktreeStatus } from './status-pace'

/** How many git processes the herd's reads keep in flight; more end together and hold the event loop as one block. */
const GIT_PROCESSES = 6

const gitSlots = createProcessSlots(GIT_PROCESSES)

const passAtOnce = async () => {}

/** `pass` is awaited in the slot right before the process starts: starting one holds the event loop as well. */
const gitAsync = (cwd: string, args: string[], pass: () => Promise<void> = passAtOnce): Promise<string | null> =>
  gitSlots.run(async () => {
    await pass()
    const child = Bun.spawn(['git', '-C', cwd, ...args], { stdout: 'pipe', stderr: 'ignore' })
    const [output, exitCode] = await Promise.all([new Response(child.stdout).text(), child.exited])
    return exitCode === 0 ? output.trim() : 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
}

/** What git says about a file in a checkout: its porcelain status and the short commit that last changed it. */
export type FileGitFacts = { status: string | null; commit: string | null }

export const fileGitFacts = (root: string, path: string): FileGitFacts => ({
  status: git(root, ['status', '--porcelain', '--', path]),
  commit: git(root, ['log', '-1', '--format=%h', '--', path]),
})

/** The text of `path` at `ref`, or null when the ref or the file does not exist there. */
export const showAtRef = (root: string, ref: string, path: string): string | null => {
  const result = Bun.spawnSync(['git', '-C', root, 'show', `${ref}:${path}`], { stdout: 'pipe', stderr: 'pipe' })
  return result.exitCode === 0 ? result.stdout.toString() : null
}

/** Whether `path` (from the repository root, without `..`) exists at `ref`. */
export const existsOnRef = (root: string, ref: string, path: string): boolean =>
  Bun.spawnSync(['git', '-C', root, 'cat-file', '-e', `${ref}:${path}`], { stdout: 'ignore', stderr: 'ignore' })
    .exitCode === 0

/** The commit `ref` points at, null when it does not exist. */
export const commitOf = (root: string, ref: string): string | null =>
  git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])

/** The commit `ref` points at, read without holding the event loop; null when it does not exist. */
export const resolveCommit = async (root: string, ref: string): Promise<string | null> =>
  (await gitAsync(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])) || null

/**
 * The commit of every ref under `namespace` (e.g. `refs/jackherd/pr`), by full ref name, read in one git call and
 * without holding the event loop; empty when there is none or no git.
 */
export const refCommits = async (root: string, namespace: string): Promise<Map<string, string>> => {
  const output = await gitAsync(root, ['for-each-ref', '--format=%(refname) %(objectname)', namespace])
  const pairs = (output ?? '').split('\n').flatMap((line) => {
    const [ref, commit] = line.split(' ')
    return ref && commit ? [[ref, commit] as const] : []
  })
  return new Map(pairs)
}

const lastChangeAt = async (root: string, commit: string, path: string): Promise<number | null> => {
  const seconds = Number(await gitAsync(root, ['log', '-1', '--format=%ct', commit, '--', path]))
  return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : null
}

/** The last-change times read per `root\0commit`, by path, the commit asked last at the end; a change at a commit never moves. */
const cachedChanges = new Map<string, Map<string, number | null>>()

const changesOf = (root: string, commit: string): Map<string, number | null> => {
  const key = `${root}\0${commit}`
  const changes = cachedChanges.get(key) ?? new Map<string, number | null>()
  cachedChanges.delete(key)
  cachedChanges.set(key, changes)
  const oldest = cachedChanges.keys().next().value
  if (cachedChanges.size > CACHED_COMMITS && oldest !== undefined) cachedChanges.delete(oldest)
  return changes
}

/**
 * A reader of the commit time, in epoch milliseconds, of the last commit at `commit` that changed each of `paths`;
 * null for a path not asked, a file unknown there or no commit. The times not kept yet are read side by side without
 * holding the event loop, and each answer is kept per commit, so a refresh while the ref stands asks git nothing and
 * a moved ref reads afresh.
 */
export const lastChangesAt = async (
  root: string,
  commit: string | null,
  paths: readonly string[],
): Promise<(path: string) => number | null> => {
  if (commit === null) return () => null
  const changes = changesOf(root, commit)
  const missing = paths.filter((path) => !changes.has(path))
  await Promise.all(missing.map(async (path) => changes.set(path, await lastChangeAt(root, commit, path))))
  return (path) => changes.get(path) ?? null
}

/** Reads files as they are at the base ref. */
export type BaseReader = (path: string) => string | null

/** How many commits keep their texts: the base ref and the heads of the open pull requests that change a plan. */
const CACHED_COMMITS = 16

/** The texts read per `root\0commit`, the one asked last at the end. */
const cachedTexts = new Map<string, Map<string, string>>()

const textsOf = (root: string, commit: string): Map<string, string> => {
  const key = `${root}\0${commit}`
  const texts = cachedTexts.get(key) ?? new Map<string, string>()
  cachedTexts.delete(key)
  cachedTexts.set(key, texts)
  const oldest = cachedTexts.keys().next().value
  if (cachedTexts.size > CACHED_COMMITS && oldest !== undefined) cachedTexts.delete(oldest)
  return texts
}

/**
 * A reader for the files at `ref`, with the commit resolved once. A file at a commit never changes, so what was
 * read is kept for as long as the commit is among the last `CACHED_COMMITS` asked: a re-read of the sprint costs
 * one `git rev-parse` per ref instead of one `git show` per plan, and the base and the pull request heads read in
 * the same round do not evict each other.
 */
export const baseReaderOf = (root: string, ref: string): BaseReader => baseReaderAt(root, commitOf(root, ref))

/** `baseReaderOf` for a commit resolved beforehand (`resolveCommit`); reads nothing without one. */
export const baseReaderAt = (root: string, commit: string | null): BaseReader => {
  if (commit === null) return () => null
  const texts = textsOf(root, commit)
  return (path) => {
    const kept = texts.get(path)
    if (kept !== undefined) return kept
    const text = showAtRef(root, commit, path)
    if (text !== null) texts.set(path, text)
    return text
  }
}

export const refExists = (root: string, ref: string): boolean => commitOf(root, ref) !== null

/** Whether `cwd` lies in a linked worktree (`git worktree add`), not in the main checkout; false outside git. */
export const isLinkedWorktree = (cwd: string): boolean => {
  const directories = git(cwd, ['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir'])?.split('\n')
  return directories?.length === 2 && directories[0] !== directories[1]
}

/** The main checkout, also when called from inside a linked worktree. */
export const mainCheckout = (cwd: string): string => {
  const commonDirectory = git(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir'])
  if (!commonDirectory) throw new Error('not inside a git checkout')
  return dirname(commonDirectory)
}

/** `mainCheckout`, null outside a git checkout instead of git's error. */
export const mainCheckoutOrNull = (cwd: string): string | null => {
  try {
    return mainCheckout(cwd)
  } catch {
    return null
  }
}

/** The top of the checkout `cwd` is in: the worktree itself, not the main checkout. */
export const worktreeRoot = (cwd: string): string => {
  const top = git(cwd, ['rev-parse', '--show-toplevel'])
  if (!top) throw new Error('not inside a git checkout')
  return top
}

const BRANCH_HEAD = '# branch.head '
const DETACHED_HEAD = '(detached)'
const HEADER_MARK = '#'

/**
 * The branch and the number of changed files, untracked ones included, in the output of `git status --porcelain=v2
 * --branch`; a detached head and a missing output have no branch.
 */
export const branchStatusOf = (output: string | null): BranchStatus => {
  const lines = (output ?? '').split('\n').filter(Boolean)
  const head = lines.find((line) => line.startsWith(BRANCH_HEAD))?.slice(BRANCH_HEAD.length)
  return {
    branch: head && head !== DETACHED_HEAD ? head : null,
    dirty: lines.filter((line) => !line.startsWith(HEADER_MARK)).length,
  }
}

/**
 * Branch and changed files of a worktree from `git status`, the dearest of the herd's git calls in a large checkout.
 * Without optional locks: the herd never rewrites the index, which would take the lock an agent's git needs and move
 * the index the worktree's stamp watches (`worktreeStamp`).
 */
const branchStatusAt = async (worktree: string, pass: () => Promise<void>): Promise<BranchStatus> =>
  branchStatusOf(await gitAsync(worktree, ['--no-optional-locks', 'status', '--porcelain=v2', '--branch'], pass))

/**
 * Branch, commits ahead of `baseRef` and changed files of a worktree; null and 0 when it does not exist. The two
 * git calls run side by side and without holding the event loop, so a key pressed meanwhile is answered at once;
 * each starts after `pass` (a `SliceGate`), so the starts of many worktrees' calls do not add up to one block. The
 * herd keeps the answer while nothing moved (`pacedStatus`).
 */
export const gitStatusOf = async (
  worktree: string,
  baseRef: string,
  pass: () => Promise<void> = passAtOnce,
): Promise<WorktreeStatus> => {
  if (!existsSync(worktree)) return { branch: null, ahead: null, dirty: 0 }
  const [count, status] = await Promise.all([
    gitAsync(worktree, ['rev-list', '--count', `${baseRef}..HEAD`], pass),
    branchStatusAt(worktree, pass),
  ])
  const ahead = Number.parseInt(count ?? '', 10)
  return { ...status, ahead: Number.isNaN(ahead) ? null : ahead }
}

/** Where this clone keeps `FETCH_HEAD`, whether it exists yet or not; null outside a git checkout. */
export const fetchHeadPath = (root: string): string | null =>
  git(root, ['rev-parse', '--path-format=absolute', '--git-path', 'FETCH_HEAD'])

/** The base ref's commit and commit time, and when this clone last fetched (the time of `FETCH_HEAD`), as far as git says. */
export const baseRefInfo = (root: string, ref: string): BaseRefInfo => {
  const fetchHead = fetchHeadPath(root)
  const fetchedAt = fetchHead && existsSync(fetchHead) ? statSync(fetchHead).mtime : null
  return {
    name: ref,
    commit: git(root, ['rev-parse', '--short', `${ref}^{commit}`]),
    committedAt: git(root, ['log', '-1', '--format=%cI', ref]),
    fetchedAt,
  }
}

const SSH_REMOTE = /^git@([^:]+):(.+?)(?:\.git)?$/

/** The remote as a plain `https://host/path` without credentials, null when it is no http(s) URL. */
const withoutCredentials = (remote: string): string | null => {
  try {
    const url = new URL(remote)
    if (url.protocol !== 'https:' && url.protocol !== 'http:') return null
    return `${url.protocol}//${url.host}${url.pathname.replace(/\.git$/, '').replace(/\/$/, '')}`
  } catch {
    return null
  }
}

/** `https://host/owner/repo/blob/<branch>/` for the `origin` remote, null when there is none or it is no URL we know. */
export const remoteBlobBase = (root: string, branch: string): string | null => {
  const remote = git(root, ['remote', 'get-url', 'origin'])
  if (!remote) return null
  const ssh = SSH_REMOTE.exec(remote)
  const base = ssh ? `https://${ssh[1]}/${ssh[2]}` : withoutCredentials(remote)
  return base ? `${base}/blob/${branch}/` : null
}

/** The commit time (epoch seconds) of the last commit on `ref` that touched `path`; null when there is none. */
export const lastCommitTime = (root: string, ref: string, path: string): number | null => {
  const seconds = Number.parseInt(git(root, ['log', '-1', '--format=%ct', ref, '--', path]) ?? '', 10)
  return Number.isNaN(seconds) ? null : seconds
}

/** The names of the directories under the worktree directory; none when it does not exist. */
export const worktreeNames = (worktreeDirectory: string): string[] =>
  existsSync(worktreeDirectory)
    ? readdirSync(worktreeDirectory, { withFileTypes: true })
        .filter((entry) => entry.isDirectory())
        .map((entry) => entry.name)
    : []
