/** `owner/name` as `repos` spells a repository. */
export const REPOSITORY_NAME = /^[\w.-]+\/[\w.-]+$/

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

/** `owner/name` of a URL path with exactly those two segments; a deeper or shorter path names no repository of ours. */
const ownerAndName = (path: string): string | null => {
  const segments = path
    .replace(/\.git\/?$/, '')
    .split('/')
    .filter((segment) => segment !== '')
  return segments.length === 2 ? segments.join('/') : null
}

/**
 * `owner/name` of a git remote URL: `git@host:owner/name(.git)`, `https://host/owner/name(.git)` (credentials
 * allowed) and `ssh://git@host(:port)/owner/name(.git)`. Null for anything else: a local path, a `file://` URL, a
 * path with more or fewer than two segments.
 */
export const repositoryOf = (remoteUrl: string): string | null => {
  const remote = remoteUrl.trim()
  const scp = SCP_REMOTE.exec(remote)
  if (scp) return `${scp[1]}/${scp[2]}`
  try {
    const url = new URL(remote)
    return ['https:', 'http:', 'ssh:'].includes(url.protocol) ? ownerAndName(url.pathname) : null
  } catch {
    return null
  }
}

/** Whether `repository` is one of `repos`; GitHub names compare without regard to case. A repository nobody could name is in none. */
export const isRepositoryIn = (repository: string | null, repos: readonly string[]): boolean =>
  repository !== null && repos.some((repo) => repo.toLowerCase() === repository.toLowerCase())

/** The repository the checkout at `root` pushes to (`origin`), null without a git repository, an origin or a URL `repositoryOf` knows. */
export const readRepositoryIdentity = (root: string): string | null => {
  const result = Bun.spawnSync(['git', '-C', root, 'remote', 'get-url', 'origin'], { stdout: 'pipe', stderr: 'ignore' })
  return result.exitCode === 0 ? repositoryOf(result.stdout.toString()) : null
}
