import type { FileEntry } from '@/types/api'

/** List chip label: owner, or owner:group when different. */
export function formatOwnerChip(item: Pick<FileEntry, 'owner' | 'group' | 'type'>): string {
  if (item.type === 'symlink') return '—'
  const o = (item.owner ?? '').trim()
  const g = (item.group ?? '').trim()
  if (!o) return '—'
  if (!g || g === o) return o
  return `${o}:${g}`
}

export function ownerChipColor(owner: string): string | undefined {
  if (owner === 'root') return 'warning'
  return undefined
}

export function permissionTooltip(item: FileEntry): string {
  const parts: string[] = []
  if (item.permissions) parts.push(item.permissions)
  if (item.mode_octal) parts.push(item.mode_octal)
  const o = (item.owner ?? '').trim()
  const g = (item.group ?? '').trim()
  if (o) parts.push(g && g !== o ? `${o}:${g}` : o)
  return parts.join(' · ') || '—'
}

export const CHMOD_PRESETS = [
  { label: '文件 644', mode: '644', for: 'file' as const },
  { label: '目录 755', mode: '755', for: 'directory' as const },
  { label: '私密 600', mode: '600', for: 'file' as const },
  { label: '协作 775', mode: '775', for: 'directory' as const },
  { label: '可执行 755', mode: '755', for: 'file' as const },
] as const

const SUDOERS_DOC = 'docs/deploy/nexus-files-sudoers.example'

/** HTTP / API message hints for permission-denied reads or writes. */
export function isPermissionDeniedMessage(message: string): boolean {
  const m = message.toLowerCase()
  return (
    m.includes('permission denied')
    || m.includes('operation not permitted')
    || m.includes('无法访问')
    || m.includes('无权限')
    || m.includes('无写入权限')
    || m.includes('读取失败')
    || m.includes('chmod 失败')
  )
}

/** Heuristic: SSH user likely cannot read this file from `ls` permission bits. */
export function isEntryLikelyUnreadable(
  item: Pick<FileEntry, 'type' | 'permissions' | 'owner' | 'group'>,
  sshUser: string | null | undefined,
): boolean {
  if (!sshUser || sshUser === 'root' || item.type !== 'file') return false
  const perms = item.permissions ?? ''
  if (perms.length < 10) return false
  const owner = (item.owner ?? '').trim()
  const group = (item.group ?? '').trim()
  const ownerTri = perms.slice(1, 4)
  const groupTri = perms.slice(4, 7)
  const otherTri = perms.slice(7, 10)
  if (owner === sshUser) return !ownerTri.includes('r')
  if (group && group === sshUser) return !groupTri.includes('r')
  return !otherTri.includes('r') && !groupTri.includes('r')
}

export function buildFilesAccessHint(params: {
  sshUser?: string | null
  canSudo: boolean
  isRootSsh: boolean
  lastReadDeniedPath?: string | null
  unreadableCount?: number
}): { type: 'warning' | 'error'; text: string } | null {
  const lines: string[] = []
  if (params.lastReadDeniedPath) {
    lines.push(`无法读取「${params.lastReadDeniedPath}」：当前 SSH 用户可能无读权限。`)
  }
  const n = params.unreadableCount ?? 0
  if (n > 0 && params.sshUser) {
    lines.push(`当前目录约 ${n} 个文件对 SSH 用户「${params.sshUser}」可能不可读（根据 ls 权限推断）。`)
  }
  if (!params.isRootSsh && !params.canSudo) {
    lines.push(
      '写权限、chmod、读取 root 属主文件等可能失败。请在目标机配置免密 sudo，或改用 root SSH。',
    )
  } else if (!params.isRootSsh && params.canSudo) {
    lines.push('部分操作将自动尝试 sudo -n（需白名单含 chmod/chown/cat 等）。')
  }
  if (!lines.length) return null
  const type: 'warning' | 'error' =
    !params.isRootSsh && !params.canSudo ? 'error' : 'warning'
  return {
    type,
    text: `${lines.join(' ')} 示例：${SUDOERS_DOC}`,
  }
}

export { SUDOERS_DOC }
