import { posix } from 'node:path'

/** Reads the file at a path relative to the package root as an address the page can show; null when it cannot. */
export type LocalImage = (relativePath: string) => string | null

const CAMO = /^https:\/\/camo\.githubusercontent\.com\/[0-9a-f]+\/([0-9a-f]+)$/
const SCHEME = /^[a-z][a-z0-9+.-]*:|^\/\//i

/** The address GitHub's image proxy stands for; any other address as it is. */
const canonicalOf = (src: string): string => {
  const hex = CAMO.exec(src)?.[1]
  return hex ? Buffer.from(hex, 'hex').toString('utf8') : src
}

/** The path below `<package>[@version]/` of an unpkg address of the package; null for any other address. */
const unpkgPathOf = (address: string, packageName: string): string | null => {
  if (!URL.canParse(address)) return null
  const { host, pathname } = new URL(address)
  const [, name, ...rest] = pathname.split('/')
  if (host !== 'unpkg.com' || name?.split('@')[0] !== packageName || rest.length === 0) return null
  return posix.normalize(rest.join('/'))
}

/**
 * The path inside the package an image address means: a relative path, or an `unpkg.com/<package>/…` address of the
 * package itself (any version, `?` part cut off). Null for every other address.
 */
export const packagePathOf = (address: string, packageName: string): string | null => {
  const clean = address.split(/[?#]/)[0]
  const unpkg = unpkgPathOf(clean, packageName)
  if (unpkg !== null) return unpkg
  if (SCHEME.test(clean) || clean.startsWith('/') || clean === '') return null
  const normalized = posix.normalize(clean)
  return normalized.startsWith('..') ? null : normalized
}

const ENTITIES: Record<string, string> = { '&amp;': '&', '&quot;': '"', '&lt;': '<', '&gt;': '>', '&#39;': "'" }

/** An attribute's text as the address it stands for, the entities GitHub's renderer writes undone. */
export const decodedAttribute = (text: string): string =>
  text.replace(/&(amp|quot|lt|gt|#39);/g, (entity) => ENTITIES[entity])

/** An address as attribute text: nothing in it can close the attribute or open a tag. */
const escapedAttribute = (text: string): string =>
  text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')

const attributeOf = (tag: string, name: string): string | null => {
  const text = new RegExp(`\\s${name}="([^"]*)"`).exec(tag)?.[1]
  return text === undefined ? null : decodedAttribute(text)
}

const withoutAttributes = (tag: string, names: readonly string[]): string =>
  names.reduce((rest, name) => rest.replace(new RegExp(`\\s${name}="[^"]*"`, 'g'), ''), tag)

/** The tag with `source` as its only address; `source` is the address itself, not attribute text, and is escaped here. */
const withSource = (tag: string, source: string): string =>
  withoutAttributes(tag, ['src', 'data-canonical-src']).replace(/^<img/, () => `<img src="${escapedAttribute(source)}"`)

const localOrKept = (address: string, packageName: string, read: LocalImage): string => {
  const path = packagePathOf(address, packageName)
  return (path === null ? null : read(path)) ?? address
}

/** One `<img>` tag with its address resolved: the working tree's file for the package's own images, the original address otherwise. */
const resolveImage = (tag: string, packageName: string, read: LocalImage): string => {
  const address = canonicalOf(attributeOf(tag, 'data-canonical-src') ?? attributeOf(tag, 'src') ?? '')
  return address === '' ? tag : withSource(tag, localOrKept(address, packageName, read))
}

const withClass = (tag: string, className: string): string => tag.replace(/^<img/, `<img class="${className}"`)

/** `<picture>` with a dark source as two images, one shown per theme; the page switches themes itself, the browser's media query would not follow it. */
const themedPicture = (picture: string): string => {
  const dark = /<source[^>]*\bsrcset="([^"]+)"/.exec(picture)?.[1]
  const image = /<img[^>]*>/.exec(picture)?.[0]
  if (dark === undefined || image === undefined) return picture
  const darkImage = withSource(image, decodedAttribute(dark))
  return `${withClass(image, 'only-light')}${withClass(darkImage, 'only-dark')}`
}

/**
 * The rendered HTML with every image shown from the working tree where it is the package's own (relative paths and
 * `unpkg.com/<package>/…`, so an unpublished README shows its unpublished pictures) and every `<picture>` split
 * into a light and a dark image. Other addresses stay as they are.
 */
export const rewriteImages = (html: string, packageName: string, read: LocalImage): string =>
  html
    .replace(/<picture>[\s\S]*?<\/picture>/g, themedPicture)
    .replace(/<img\b[^>]*>/g, (tag) => resolveImage(tag, packageName, read))
