import type { GhAnswer, GhOptions } from '../watch/gh'

export type GhRunner = (args: string[], cwd: string, options?: GhOptions) => Promise<GhAnswer>

/** Names the `owner/repo` of a git remote address (ssh or https, `.git` optional); null for anything else. */
export const repositorySlugOf = (remote: string): string | null =>
  /^git@[^:]+:([^/]+\/[^/]+?)(?:\.git)?$/.exec(remote.trim())?.[1] ??
  /^https?:\/\/[^/]+\/([^/]+\/[^/]+?)(?:\.git)?\/?$/.exec(remote.trim())?.[1] ??
  null

const MISSING_GH =
  'the GitHub CLI `gh` is not installed: install it from https://cli.github.com, then run `gh auth login`'
const NOT_SIGNED_IN = 'the GitHub CLI is not signed in: run `gh auth login`, then try again'

/** The reason a `gh` call failed, with the step that fixes it when it is the missing CLI or the missing login. */
export const ghFailure = (error: string): string => {
  if (/ENOENT|not found|not installed|No such file/i.test(error)) return MISSING_GH
  if (/gh auth login|HTTP 401|not logged|authentication/i.test(error)) return NOT_SIGNED_IN
  return `GitHub's markdown API failed: ${error}`
}

/**
 * The HTML GitHub renders for `markdown` (flavor `gfm`, with the repository as context when known). The request body
 * goes in through standard input: a long document as an argument exceeds the operating system's limit (`E2BIG`).
 * Throws with the missing step.
 */
export const renderMarkdown = async (
  markdown: string,
  repositorySlug: string | null,
  cwd: string,
  gh: GhRunner,
): Promise<string> => {
  const body = JSON.stringify({
    text: markdown,
    mode: 'gfm',
    ...(repositorySlug === null ? {} : { context: repositorySlug }),
  })
  const answer = await gh(['api', '/markdown', '--input', '-'], cwd, { stdin: body })
  if (!answer.ok) throw new Error(ghFailure(answer.error))
  return answer.stdout
}
