/** 轻量路径工具，供渲染进程 Markdown 使用（避免依赖 node:path 打包问题）。 */

export function dirnamePath(filePath: string): string {
  const n = filePath.replace(/\\/g, '/')
  const i = n.lastIndexOf('/')
  if (i < 0) return '.'
  const d = n.slice(0, i)
  if (/^[A-Za-z]:$/.test(d)) return `${d}/`
  return d || '/'
}

/** 去掉 . /.. 的段落归一化（不含盘符）。 */
export function normalizeDotSegments(pathWithoutDrive: string): string {
  const segs = pathWithoutDrive.split('/').filter((s) => s && s !== '.')
  const st: string[] = []
  for (const s of segs) {
    if (s === '..') st.pop()
    else st.push(s)
  }
  return st.join('/')
}

/** 将相对 href 解析为绝对本地路径（正斜杠）。 */
export function resolvePathFromBaseFile(baseFilePath: string, href: string): string {
  let h = href.trim().replace(/\\/g, '/')
  const q = h.indexOf('?')
  if (q >= 0) h = h.slice(0, q)
  const hash = h.indexOf('#')
  if (hash >= 0) h = h.slice(0, hash)

  const baseNorm = baseFilePath.replace(/\\/g, '/')
  const winBase = baseNorm.match(/^([A-Za-z]:)\/(.*)$/)

  if (/^[A-Za-z]:\//i.test(h)) {
    const m = h.match(/^([A-Za-z]:\/)(.*)$/)!
    return `${m[1]}${normalizeDotSegments(m[2] ?? '')}`
  }

  if (h.startsWith('/')) {
    if (winBase) {
      return `${winBase[1]}/${normalizeDotSegments(h.slice(1))}`
    }
    return `/${normalizeDotSegments(h.slice(1))}`
  }

  const dir = dirnamePath(baseNorm)
  const joined = dir.endsWith('/') ? `${dir}${h}` : `${dir}/${h}`

  if (winBase) {
    const m = joined.match(/^([A-Za-z]:\/)(.*)$/)
    if (m) return `${m[1]}${normalizeDotSegments(m[2] ?? '')}`
  }
  if (joined.startsWith('/')) return `/${normalizeDotSegments(joined.slice(1))}`
  return normalizeDotSegments(joined)
}

/** 绝对路径 → file:// URL（Windows / Unix）。 */
export function absolutePathToFileUrl(absPath: string): string {
  const norm = absPath.replace(/\\/g, '/').trim()
  if (!norm) return ''
  if (/^[A-Za-z]:\//.test(norm)) {
    return `file:///${encodeURI(norm)}`
  }
  const withLead = norm.startsWith('/') ? norm : `/${norm}`
  return `file://${encodeURI(withLead)}`
}
