import type { DriveFileInfo } from "@/lib/api/types"
import { isUltidocPath } from "@/lib/drive/richtext-formats"

function normalizePath(path: string): string {
  const p = path.replace(/\/+/g, "/")
  if (!p.startsWith("/")) return `/${p}`
  return p
}

function fileName(path: string): string {
  const normalized = normalizePath(path)
  const slash = normalized.lastIndexOf("/")
  return slash >= 0 ? normalized.slice(slash + 1) : normalized
}

function parentDir(path: string): string {
  const normalized = normalizePath(path)
  if (normalized === "/") return "/"
  const slash = normalized.lastIndexOf("/")
  return slash <= 0 ? "/" : normalized.slice(0, slash)
}

function documentBase(name: string): string {
  if (isUltidocPath(name)) {
    return name.slice(0, -(`.ultidoc.json`.length))
  }
  const dot = name.lastIndexOf(".")
  return dot > 0 ? name.slice(0, dot) : name
}

function sidecarSourceKey(path: string): string {
  return `${parentDir(path)}\0${documentBase(fileName(path)).toLowerCase()}`
}

/** Hide .ultidoc.json sidecars when their source file is in the same folder listing. */
export function filterHiddenDriveSidecars(items: DriveFileInfo[]): DriveFileInfo[] {
  if (items.length === 0) return items

  const sources = new Set<string>()
  for (const item of items) {
    if (item.type === "directory" || isUltidocPath(item.name)) continue
    sources.add(sidecarSourceKey(item.path))
  }

  return items.filter((item) => {
    if (item.type === "directory" || !isUltidocPath(item.name)) return true
    return !sources.has(sidecarSourceKey(item.path))
  })
}
