import { pathToFileURL } from "bun"
import path from "path"

export function removeLineRange(input: string) {
  const hashIndex = input.lastIndexOf("#")
  return hashIndex !== -1 ? input.substring(0, hashIndex) : input
}

export function extractLineRange(input: string) {
  const hashIndex = input.lastIndexOf("#")
  if (hashIndex === -1) return { baseQuery: input }

  const baseName = input.substring(0, hashIndex)
  const linePart = input.substring(hashIndex + 1)
  const lineMatch = linePart.match(/^(\d+)(?:-(\d*))?$/)
  if (!lineMatch) return { baseQuery: baseName }

  const startLine = Number(lineMatch[1])
  const endLine = lineMatch[2] && startLine < Number(lineMatch[2]) ? Number(lineMatch[2]) : undefined

  return {
    lineRange: { baseName, startLine, endLine },
    baseQuery: baseName,
  }
}

export function createFilePart(
  item: string,
  syncPath: string,
  lineRange?: { startLine: number; endLine?: number },
) {
  const baseDir = (syncPath || process.cwd()).replace(/\/+$/, "")
  const fullPath = path.isAbsolute(item) ? item : path.join(baseDir, item)
  const urlObj = pathToFileURL(fullPath)
  const filename =
    lineRange && !item.endsWith("/")
      ? `${item}#${lineRange.startLine}${lineRange.endLine ? `-${lineRange.endLine}` : ""}`
      : item

  if (lineRange && !item.endsWith("/")) {
    urlObj.searchParams.set("start", String(lineRange.startLine))
    if (lineRange.endLine !== undefined) urlObj.searchParams.set("end", String(lineRange.endLine))
  }

  return {
    filename,
    url: urlObj.href,
    part: {
      type: "file" as const,
      mime: "text/plain",
      filename,
      url: urlObj.href,
      source: {
        type: "file" as const,
        text: { start: 0, end: 0, value: "" },
        path: item,
      },
    },
  }
}

export function normalizeMentionPath(filePath: string, baseDir: string) {
  const absolute = path.resolve(filePath)
  const relative = path.relative(baseDir, absolute)
  if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) {
    return relative.split(path.sep).join("/")
  }
  return absolute.split(path.sep).join("/")
}
