import { errorText } from './error-text'
import { PULL_REQUEST_FIELDS, type PullRequest, parsePullRequests, pullRequestsByBranch } from './pull-requests'

/** Open pull requests by head branch, or none with the reason when `gh` fails. */
export type PullRequestState = { byBranch: Map<string, PullRequest[]>; errors: string[] }

/** What `gh` answered: stdout on success, else the reason. */
export type GhAnswer = { ok: true; stdout: string } | { ok: false; reason: string }

export const noPullRequests = (): PullRequestState => ({ byBranch: new Map(), errors: [] })

/** The GitHub host whose pull request links are trusted; `GH_HOST` names an Enterprise server. */
export const GITHUB_HOST = process.env.GH_HOST ?? 'github.com'

const runGh = async (args: readonly string[], root: string): Promise<GhAnswer> => {
  const child = Bun.spawn(['gh', ...args], { cwd: root, stdout: 'pipe', stderr: 'pipe' })
  const [stdout, stderr, exitCode] = await Promise.all([
    new Response(child.stdout).text(),
    new Response(child.stderr).text(),
    child.exited,
  ])
  return exitCode === 0 ? { ok: true, stdout } : { ok: false, reason: stderr.trim() || `exit ${exitCode}` }
}

/** Runs `gh`; never rejects, also not when `gh` is not installed, and the reason is terminal-safe. */
const askGh = async (args: readonly string[], root: string): Promise<GhAnswer> => {
  try {
    const answer = await runGh(args, root)
    return answer.ok ? answer : { ok: false, reason: errorText(answer.reason) }
  } catch (error) {
    return { ok: false, reason: errorText(error) }
  }
}

/** Open pull requests, or none with the reason; never rejects, also not when `gh` is not installed. */
export const fetchPullRequests = async (root: string): Promise<PullRequestState> => {
  const answer = await askGh(['pr', 'list', '--state', 'open', '--limit', '100', '--json', PULL_REQUEST_FIELDS], root)
  if (!answer.ok) return { byBranch: new Map(), errors: [`gh pr list: ${answer.reason}`] }
  try {
    return { byBranch: pullRequestsByBranch(parsePullRequests(answer.stdout, GITHUB_HOST)), errors: [] }
  } catch (error) {
    return { byBranch: new Map(), errors: [errorText(error)] }
  }
}
