/**
 * Remote SSH path helpers for Files page (normalize, join, breadcrumbs).
 */

/** Default browse root on managed servers (宝塔站点根目录). */
export const DEFAULT_FILES_ROOT = '/www/wwwroot'

export interface RemoteBreadcrumbItem {
  title: string
  path: string
  disabled: boolean
}

/** Normalize user/SSH path: leading slash, no duplicate slashes, no trailing slash (except root). */
export function normalizeRemotePath(path: string): string {
  const trimmed = (path ?? '').trim().replace(/\\/g, '/')
  if (!trimmed || trimmed === '.') return '/'
  let p = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
  p = p.replace(/\/+/g, '/')
  if (p.length > 1 && p.endsWith('/')) {
    p = p.slice(0, -1)
  }
  return p
}

export function splitRemotePath(path: string): string[] {
  return normalizeRemotePath(path).split('/').filter(Boolean)
}

/** Join base path with a single segment (not a nested path). */
export function joinRemotePath(base: string, segment: string): string {
  const normBase = normalizeRemotePath(base)
  const seg = segment.replace(/\/+/g, '').trim()
  if (!seg || seg === '.') return normBase
  if (seg === '..') {
    const parts = splitRemotePath(normBase)
    parts.pop()
    return parts.length ? `/${parts.join('/')}` : '/'
  }
  return normBase === '/' ? `/${seg}` : `${normBase}/${seg}`
}

/** Parent directory, or null when already at root. */
export function parentRemotePath(path: string): string | null {
  const parts = splitRemotePath(path)
  if (!parts.length) return null
  parts.pop()
  return parts.length ? `/${parts.join('/')}` : '/'
}

/** Validate a single file/dir name segment (not a full path). */
export function validatePathSegment(name: string): string | true {
  const trimmed = name.trim()
  if (!trimmed) return '名称不能为空'
  if (trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes('\0')) {
    return '名称不能包含路径分隔符'
  }
  if (trimmed === '.' || trimmed === '..') return '非法名称'
  return true
}

export function buildRemoteBreadcrumbs(currentPath: string): RemoteBreadcrumbItem[] {
  const normalized = normalizeRemotePath(currentPath)
  const segments = splitRemotePath(normalized)
  const items: RemoteBreadcrumbItem[] = [
    {
      title: '/',
      path: '/',
      disabled: segments.length === 0,
    },
  ]
  let acc = ''
  for (let i = 0; i < segments.length; i++) {
    acc = joinRemotePath(acc || '/', segments[i])
    items.push({
      title: segments[i],
      path: acc,
      disabled: i === segments.length - 1,
    })
  }
  return items
}
