/**
 * 文件操作 Composable
 * 提供文件读取、写入、删除等基础操作，包括 ZIP 文件浏览
 */

import { Message } from '@arco-design/web-vue'
import { getPathSeparator } from '@/utils/fileUtils'
import {
  listDir,
  readFile as readFileApi,
  writeFile as writeFileApi,
  deletePath as deletePathApi,
  createFile,
  createDir,
  renamePath as renamePathApi,
  listZipContents as listZipContentsApi,
  extractFileFromZip,
  extractFileFromZipToTemp as extractZipToTempApi,
  getFileServerURL as getFileServerUrlApi
} from '@/api'
import type { FileItem, FileOperationResult } from '@/types/file-system'

export interface UseFileOperationsOptions {
  onSuccess?: (operation: string, data: any) => void
  onError?: (operation: string, error: Error) => void
}

/**
 * 文件操作结果
 */
export function useFileOperations(options: UseFileOperationsOptions = {}) {
  const { onSuccess, onError } = options

  /**
   * 列出目录内容
   */
  const listDirectory = async (path: string): Promise<FileItem[]> => {
    try {
      const result = await listDir(path)
      onSuccess?.('listDirectory', result)
      return result
    } catch (error) {
      const err = error as Error
      onError?.('listDirectory', err)
      throw err
    }
  }

  /**
   * 读取文件内容
   */
  const readFile = async (path: string): Promise<string> => {
    try {
      const content = await readFileApi(path)
      onSuccess?.('readFile', { path, size: content.length })
      return content
    } catch (error) {
      const err = error as Error
      onError?.('readFile', err)
      throw err
    }
  }

  /**
   * 写入文件内容
   */
  const writeFile = async (
    path: string,
    content: string,
    createBackup: boolean = false
  ): Promise<void> => {
    try {
      await writeFileApi(path, content)
      onSuccess?.('writeFile', { path, size: content.length })
    } catch (error) {
      const err = error as Error
      onError?.('writeFile', err)
      throw err
    }
  }

  /**
   * 删除路径（文件或目录），返回被删除的文件信息
   */
  const deletePath = async (path: string): Promise<FileItem> => {
    try {
      const result = await deletePathApi(path)
      onSuccess?.('deletePath', { path, result })
      return result as FileItem
    } catch (error) {
      const err = error as Error
      onError?.('deletePath', err)
      throw err
    }
  }

  /**
   * 创建新文件，返回创建的文件信息
   */
  const createNewFile = async (
    dirPath: string,
    filename: string
  ): Promise<FileItem> => {
    try {
      const result = await createFile(dirPath, filename)
      onSuccess?.('createFile', { dirPath, filename, result })
      return result as FileItem
    } catch (error) {
      const err = error as Error
      onError?.('createFile', err)
      throw err
    }
  }

  /**
   * 创建新目录，返回创建的目录信息
   */
  const createNewDir = async (parentPath: string, dirname: string): Promise<FileItem> => {
    try {
      const result = await createDir(parentPath, dirname)
      onSuccess?.('createDir', { parentPath, dirname, result })
      return result as FileItem
    } catch (error) {
      const err = error as Error
      onError?.('createDir', err)
      throw err
    }
  }

  /**
   * 重命名文件或目录，返回新文件信息
   */
  const rename = async (oldPath: string, newName: string): Promise<FileItem> => {
    // 构造新路径
    const separator = getPathSeparator(oldPath)
    const parentPath = oldPath.substring(
      0,
      Math.max(oldPath.lastIndexOf('\\'), oldPath.lastIndexOf('/'))
    )
    const newPath = parentPath + separator + newName

    try {
      const result = await renamePathApi(oldPath, newPath)
      onSuccess?.('rename', { oldPath, newPath, result })
      return result as FileItem
    } catch (error) {
      const err = error as Error
      onError?.('rename', err)
      throw err
    }
  }

  /**
   * 复制文件或目录
   */
  const copy = async (fromPath: string, toPath: string): Promise<void> => {
    try {
      // TODO: 实现复制逻辑
      Message.warning('复制功能暂未实现')
      onSuccess?.('copy', { fromPath, toPath })
    } catch (error) {
      const err = error as Error
      onError?.('copy', err)
      throw err
    }
  }

  /**
   * 移动文件或目录
   */
  const move = async (fromPath: string, toPath: string): Promise<void> => {
    try {
      // TODO: 实现移动逻辑
      Message.warning('移动功能暂未实现')
      onSuccess?.('move', { fromPath, toPath })
    } catch (error) {
      const err = error as Error
      onError?.('move', err)
      throw err
    }
  }

  /**
   * 列出 ZIP 文件内容
   */
  const listZipContents = async (zipPath: string): Promise<FileItem[]> => {
    try {
      const result = await listZipContentsApi(zipPath)
      onSuccess?.('listZipContents', { zipPath, count: result.length })
      return result
    } catch (error) {
      const err = error as Error
      onError?.('listZipContents', err)
      throw err
    }
  }

  /**
   * 从 ZIP 中提取文件内容（文本）
   */
  const extractZipFile = async (zipPath: string, filePath: string): Promise<string> => {
    try {
      const content = await extractFileFromZip(zipPath, filePath)
      onSuccess?.('extractZipFile', { zipPath, filePath, size: content.length })
      return content
    } catch (error) {
      const err = error as Error
      onError?.('extractZipFile', err)
      throw err
    }
  }

  /**
   * 从 ZIP 中提取文件到临时目录（二进制文件，如图片）
   */
  const extractZipFileToTemp = async (zipPath: string, filePath: string): Promise<string> => {
    try {
      const tempPath = await extractZipToTempApi(zipPath, filePath)
      onSuccess?.('extractZipFileToTemp', { zipPath, filePath, tempPath })
      return tempPath
    } catch (error) {
      const err = error as Error
      onError?.('extractZipFileToTemp', err)
      throw err
    }
  }

  /**
   * 获取文件服务器 URL
   */
  const getFileServerURL = async (): Promise<string> => {
    try {
      const url = await getFileServerUrlApi()
      onSuccess?.('getFileServerURL', { url })
      return url
    } catch (error) {
      const err = error as Error
      onError?.('getFileServerURL', err)
      throw err
    }
  }

  return {
    // 基础操作
    listDirectory,
    readFile,
    writeFile,
    deletePath,

    // 创建操作
    createNewFile,
    createNewDir,

    // 高级操作
    rename,
    copy,
    move,

    // ZIP 操作
    listZipContents,
    extractZipFile,
    extractZipFileToTemp,
    getFileServerURL
  }
}

// 注意：FileItem 类型已统一定义在 @/types/file-system.ts