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

/** 是否为 Windows 磁盘绝对路径（如 `C:/Users/...`）。 */
export function isAbsDiskPath(p: string): boolean {
  return /^[A-Za-z]:\//.test(p.replace(/\\/g, '/'))
}

/** 归一化为正斜杠绝对路径（保留盘符）。 */
export function normalizeAbsPath(p: string): string {
  let n = p.trim().replace(/\\/g, '/')
  if (!n) return n
  const win = n.match(/^([A-Za-z]:)\/(.*)$/)
  if (win) {
    const drive = win[1]!.toUpperCase()
    const tail = normalizeDotSegments(win[2] ?? '')
    return tail ? `${drive}/${tail}` : `${drive}/`
  }
  if (n.startsWith('/')) {
    const tail = normalizeDotSegments(n.slice(1))
    return tail ? `/${tail}` : '/'
  }
  return normalizeDotSegments(n)
}

export function joinAbsPath(dir: string, rel: string): string {
  const base = normalizeAbsPath(dir).replace(/\/+$/, '')
  const tail = rel.replace(/^[/\\]+/, '')
  return tail ? normalizeAbsPath(`${base}/${tail}`) : base
}

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)
}

/** VFS 根路径，如 `/项目名`。 */
export function vfsRootFromPath(filePath: string): string {
  const parts = filePath.replace(/\\/g, '/').split('/').filter(Boolean)
  return parts.length > 0 ? `/${parts[0]}` : '/'
}

export function joinVfsPath(dir: string, rel: string): string {
  const base = dir.replace(/\\/g, '/').replace(/\/+$/, '')
  const tail = rel.replace(/^\/+/, '')
  return tail ? `${base}/${tail}` : base
}

/** 归一化 VFS 路径（`/a/../b` → `/b`）。 */
export function normalizeVfsPath(p: string): string {
  const parts = p.replace(/\\/g, '/').split('/').filter(Boolean)
  const st: string[] = []
  for (const part of parts) {
    if (part === '..') {
      if (st.length) st.pop()
    } else if (part !== '.') {
      st.push(part)
    }
  }
  return st.length ? `/${st.join('/')}` : '/'
}

/**
 * 将 Markdown 内链解析为 VFS 路径（Web 虚拟路径，非磁盘绝对路径）。
 * `/plans/foo.md` 相对当前已打开项目根，而非系统根。
 */
export function resolveVfsPath(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 base = baseFilePath.replace(/\\/g, '/')

  if (/^https?:\/\//i.test(h) || /^mailto:/i.test(h) || /^tel:/i.test(h)) return h
  if (/^(blob:|data:|file:)/i.test(h)) return h

  if (/^[A-Za-z]:\//i.test(h)) return normalizeVfsPath(h)

  if (h.startsWith('/')) {
    const root = vfsRootFromPath(base)
    return normalizeVfsPath(joinVfsPath(root, h.slice(1)))
  }

  const dir = dirnamePath(base)
  return normalizeVfsPath(joinVfsPath(dir, h))
}

/** `file:///C:/path/to.png` → `C:/path/to.png` */
export function fileUrlToPath(url: string): string {
  let u = url.trim()
  if (!/^file:/i.test(u)) return u
  u = u.replace(/^file:\/+/, '')
  if (/^\/[A-Za-z]:/.test(u)) u = u.slice(1)
  try {
    return decodeURIComponent(u)
  } catch {
    return u
  }
}

export function pathBasename(p: string): string {
  const n = p.replace(/\\/g, '/').replace(/\/+$/, '')
  const i = n.lastIndexOf('/')
  return i >= 0 ? n.slice(i + 1) : n
}

/** Windows 下路径比较（忽略大小写）。 */
export function pathsEqual(a: string, b: string): boolean {
  const na = normalizeAbsPath(a)
  const nb = normalizeAbsPath(b)
  if (na === nb) return true
  if (isAbsDiskPath(na) && isAbsDiskPath(nb)) {
    return na.toLowerCase() === nb.toLowerCase()
  }
  return false
}

/** 绝对路径 → 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)}`
}
