import { ARTIFACT_LINK_KIND, type LinkKind } from '../config/link-kinds'
import { type BoundedMemo, boundedMemo } from '../shared/bounded-memo'
import { plain } from './markdown-text'

/** A link of a plan that matches a link kind, as the sprint page shows it. */
export type LinkChip = { url: string; label: string; icon: string; private: boolean }

type Found = { url: string; text: string | null; before: string; line: string }

const MARKDOWN_LINK = /\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g
const AUTOLINK = /<(https?:\/\/[^>\s]+)>/g
const BARE_LINK = /(?<![<\w"])(https?:\/\/[^\s)>\]]+)/g
const LABEL_BEFORE = /\*\*([^*]+?):?\*\*:?\s*(?:[-–>]\s*)?$/
const PRIVATE = /\bprivat/i
const CONTROL = /\p{Cc}/gu

const linksOf = (line: string): Found[] => {
  if (!line.includes('http')) return []
  const found: Found[] = []
  const take = (url: string, text: string | null, index: number) =>
    found.push({ url, text, before: line.slice(0, index), line })
  for (const match of line.matchAll(MARKDOWN_LINK)) take(match[2], match[1], match.index)
  for (const match of line.matchAll(AUTOLINK)) take(match[1], null, match.index)
  const rest = line
    .replace(MARKDOWN_LINK, (whole) => ' '.repeat(whole.length))
    .replace(AUTOLINK, (whole) => ' '.repeat(whole.length))
  for (const match of rest.matchAll(BARE_LINK)) take(match[1].replace(/[.,;]+$/, ''), null, match.index)
  return found.sort((left, right) => line.indexOf(left.url) - line.indexOf(right.url))
}

const LIST_LEAD = /^\s*(?:[-*>]\s*)*(?:\[[ xX]\]\s*)?/
const LEFTOVER_LINK = /\bhttps?:\/\/\S+/g
const TITLE_END = /[\s:,;.\-–>(]+$/

/** What a line says besides its links, without list marks, checkbox and emphasis: the title of a bare artifact link. */
const lineTitleOf = ({ line }: Found): string =>
  plain(line.replace(MARKDOWN_LINK, '$1').replace(AUTOLINK, '').replace(LEFTOVER_LINK, '').replace(LIST_LEAD, ''))
    .replace(CONTROL, '')
    .replace(TITLE_END, '')
    .trim()

const labelOf = (found: Found, kind: LinkKind): string => {
  const written = found.text ?? LABEL_BEFORE.exec(found.before)?.[1]
  const own = written && plain(written).replace(CONTROL, '').trim()
  if (own) return own
  return (kind.pattern === ARTIFACT_LINK_KIND.pattern && lineTitleOf(found)) || kind.label
}

/** How many texts the chips are kept for, per list of kinds; the kept ones are dropped all at once when they are too many. */
const KEPT_TEXTS = 200

const keptChips = new WeakMap<readonly LinkKind[], BoundedMemo<string, LinkChip[]>>()

/** `extractLinkChips` without its cache, for a reader that goes through more texts than the cache keeps. */
export const readLinkChips = (markdown: string, kinds: readonly LinkKind[]): LinkChip[] => {
  const compiled = kinds.map((kind) => ({ kind, pattern: new RegExp(kind.pattern) }))
  const chips = new Map<string, LinkChip>()
  for (const line of markdown.split('\n')) {
    for (const link of linksOf(line)) {
      const match = compiled.find(({ pattern }) => pattern.test(link.url))
      if (!match || chips.has(link.url)) continue
      chips.set(link.url, {
        url: link.url,
        label: labelOf(link, match.kind),
        icon: match.kind.icon,
        private: PRIVATE.test(link.line),
      })
    }
  }
  return [...chips.values()]
}

/**
 * The links of a plan's text that match one of the kinds, once each and in the order they appear. The chip's
 * text is the link text, else the bold label written before the link (`**Mockup:** <url>`), else the kind's
 * label; a link on a line that says it is private carries that. Nothing is fetched. The chips are kept per text
 * and list of kinds, so a refresh and lanes sharing a plan get the same array back: callers must not change it.
 */
export const extractLinkChips = (markdown: string, kinds: readonly LinkKind[]): LinkChip[] => {
  const byText = keptChips.get(kinds) ?? boundedMemo<string, LinkChip[]>(KEPT_TEXTS)
  keptChips.set(kinds, byText)
  return byText.get(markdown) ?? byText.set(markdown, readLinkChips(markdown, kinds))
}

const CHIP_KEY = /^chip>(https?:\/\/.+)$/
const PLAN_KEY = /^plan>(file:\/\/\/.+)$/

/**
 * The click target of a chip. A `file:` address is the sprint page's own (the plan chip) and gets a key of its
 * own, so no link of a plan's text can ever be taken for it; the keys cannot collide with a lane key (`@`), a
 * phase key or a pull request key.
 */
export const chipKey = (url: string): string => (url.startsWith('file:') ? `plan>${url}` : `chip>${url}`)

/** The address behind the click target of a link of a plan's text: http(s) only, null for any other key. */
export const chipUrlOf = (key: string): string | null => CHIP_KEY.exec(key)?.[1] ?? null

/** The `file:` address behind the plan chip's click target; the caller opens it only when it is the page. */
export const planUrlOf = (key: string): string | null => PLAN_KEY.exec(key)?.[1] ?? null

/** Whether a click target belongs to a chip, of either kind. */
export const isChipKey = (key: string): boolean => chipUrlOf(key) !== null || planUrlOf(key) !== null
