import { extractMediaKeysFromHtml } from "@/lib/r2-storage"
import { MEDIA_FILE_BASE } from "@/lib/media-manager/file-names"
import { toArticleFolderSegment } from "@/lib/media-manager/paths"

/** Matches `content-images1`, `content-images12`, … */
const CONTENT_IMAGE_FILE_RE = /^content-images(\d+)$/

/** Legacy: `content-images`, `content-images-2`, … */
const LEGACY_CONTENT_IMAGE_FILE_RE = /^content-images(?:-(\d+))?$/

function articleContentImagesPrefix(slug: string): string {
  return `articles/${toArticleFolderSegment(slug)}/content-images`
}

function contentImageNumberFromFilePart(filePart: string, baseName: string): number | null {
  if (filePart === baseName) return 1

  const numbered = filePart.match(CONTENT_IMAGE_FILE_RE)
  if (numbered) {
    const n = Number(numbered[1])
    return Number.isInteger(n) && n >= 1 ? n : null
  }

  const legacy = filePart.match(LEGACY_CONTENT_IMAGE_FILE_RE)
  if (legacy) {
    const n = legacy[1] ? Number(legacy[1]) : 1
    return Number.isInteger(n) && n >= 1 ? n : null
  }

  return null
}

/** Next zero-based index for a new content image in this article. */
export function nextContentImageFileIndex(slug: string, htmlContents: string[]): number {
  const prefix = `${articleContentImagesPrefix(slug)}/`
  const baseName = MEDIA_FILE_BASE.contentImages
  let maxIndex = -1

  for (const html of htmlContents) {
    const keys = extractMediaKeysFromHtml(html, { prefix: "articles" })
    for (const key of keys) {
      if (!key.startsWith(prefix)) continue
      const filePart = key.slice(prefix.length).replace(/\.[^.]+$/, "")
      const n = contentImageNumberFromFilePart(filePart, baseName)
      if (n === null) continue
      maxIndex = Math.max(maxIndex, n - 1)
    }
  }

  return maxIndex + 1
}
