/**
 * 系统常用路径 Composable
 * 提供系统路径获取和快捷访问路径管理
 */

import { ref } from 'vue'
import { PATH_ICONS } from '@/utils/constants'
import { getCommonPaths } from '@/api/system'
import { connectionManager } from '@/api/connection-manager'
import type { ShortcutPath } from '@/types/file-system'

export function useCommonPaths() {
  const commonPaths = ref<ShortcutPath[]>([])
  const systemPaths = ref<Record<string, string>>({})

  const loadCommonPaths = async () => {
    try {
      // SFTP 未连接时返回默认路径，避免 requireConn 抛错；已连接则获取真实远程路径
      if (connectionManager.isSftp() && connectionManager.state !== 'connected') {
        const fallback: ShortcutPath[] = [
          { name: `${PATH_ICONS.HOME} 主目录`, path: '/root' },
          { name: `${PATH_ICONS.ROOT} 根目录`, path: '/' },
          { name: '/tmp', path: '/tmp' },
        ]
        commonPaths.value = fallback
        systemPaths.value = { home: '/root', tmp: '/tmp', root: '/' }
        return
      }
      const paths = await getCommonPaths()
      if (!paths) throw new Error('无法获取系统路径')

      systemPaths.value = paths
      const pathList: ShortcutPath[] = []
      // 根据返回数据判断平台（Linux agent 返回 root key，Windows 返回 root_ 前缀）
      const isWin = !!Object.keys(paths).find(k => k.startsWith('root_'))

      if (isWin) {
        if (paths.desktop) pathList.push({ name: `${PATH_ICONS.DESKTOP} 桌面`, path: paths.desktop })
        if (paths.documents) pathList.push({ name: `${PATH_ICONS.DOCUMENTS} 文档`, path: paths.documents })
        if (paths.downloads) pathList.push({ name: `${PATH_ICONS.DOWNLOADS} 下载`, path: paths.downloads })
        if (paths.home) pathList.push({ name: `${PATH_ICONS.HOME} 用户目录`, path: paths.home })
        const drives: Array<{ letter: string; path: string }> = []
        for (const key in paths) {
          if (key.startsWith('root_')) {
            drives.push({ letter: key.substring(5), path: paths[key] })
          }
        }
        drives.sort((a, b) => a.letter.localeCompare(b.letter))
        drives.forEach(d => pathList.push({ name: `${PATH_ICONS.DRIVE} ${d.letter}盘`, path: d.path }))
      } else {
        // Linux 远程模式
        if (paths.home) pathList.push({ name: `${PATH_ICONS.HOME} 主目录`, path: paths.home })
        if (paths.root) pathList.push({ name: `${PATH_ICONS.ROOT} 根目录`, path: '/' })
        if (paths.users) pathList.push({ name: `👥 /home`, path: paths.users })
      }

      commonPaths.value = pathList.length > 0 ? pathList : (
        connectionManager.isRemote()
          ? [{ name: `${PATH_ICONS.ROOT} 根目录`, path: '/' }]
          : [{ name: '💿 C盘', path: 'C:\\' }, { name: '💿 D盘', path: 'D:\\' }]
      )
    } catch (error) {
      console.error('加载系统路径失败:', error)
      commonPaths.value = connectionManager.isRemote()
        ? [{ name: `${PATH_ICONS.ROOT} 根目录`, path: '/' }]
        : [{ name: '💿 C盘', path: 'C:\\' }, { name: '💿 D盘', path: 'D:\\' }]
    }
  }

  return { commonPaths, systemPaths, loadCommonPaths }
}
