package com.all.pdfreader.pro.app.util

import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import com.all.pdfreader.pro.app.PRApp
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.model.DeleteResult
import com.all.pdfreader.pro.app.util.FileUtils.formatFileSize
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.collections.forEach

object FileDeleteUtil {
    /**
     * 删除文件（同步版本）- 功能完善的删除方法
     *
     * @param file 要删除的文件
     * @param deleteEmptyParentDirs 是否删除空的父目录（默认false）
     * @param dryRun 是否只模拟删除不实际执行（默认false）
     * @return DeleteResult对象，包含删除结果和详细信息
     */
    fun deleteFile(
        file: File,
        deleteEmptyParentDirs: Boolean = false,
        dryRun: Boolean = false
    ): DeleteResult {
        if (!file.exists()) {
            Log.e("ocean", "❌ File does not exist: ${file.path}")
            return DeleteResult.failure(PRApp.getStringRes(R.string.error_file_not_exist))
        }

        if (!file.canWrite()) {
            Log.e("ocean", "❌ No write permission for file: ${file.path}")
            return DeleteResult.failure(PRApp.getStringRes(R.string.error_no_write_permission))
        }

        // 安全检查：防止删除重要系统目录
        if (isProtectedPath(file)) {
            Log.e("ocean", "❌ Cannot delete protected path: ${file.path}")
            return DeleteResult.failure(PRApp.getStringRes(R.string.error_cannot_delete_protected_path))
        }

        // 如果是目录，检查是否为空（避免误删非空目录）
        if (file.isDirectory) {
            val files = file.listFiles()
            if (!files.isNullOrEmpty()) {
                Log.e("ocean", "❌ Directory is not empty: ${file.path} (${files.size} items)")
                return DeleteResult.failure(PRApp.getStringRes(R.string.error_directory_not_empty))
            }
        }

        // 计算要删除的文件大小
        val fileSize = file.length()

        if (dryRun) {
            Log.d("ocean", "🔍 Dry run - would delete: ${file.path} (${formatFileSize(fileSize)})")
            return DeleteResult.success(1, fileSize)
        }

        return try {
            val success = file.delete()
            if (success) {
                Log.d(
                    "ocean",
                    "✅ File deleted successfully: ${file.path} (${formatFileSize(fileSize)})"
                )

                // 如果需要，删除空的父目录
                if (deleteEmptyParentDirs) {
                    deleteEmptyParentDirectories(file.parentFile)
                }

                DeleteResult.success(1, fileSize)
            } else {
                Log.e("ocean", "❌ Failed to delete file: ${file.path}")
                DeleteResult.failure(PRApp.getStringRes(R.string.error_failed_delete_file))
            }
        } catch (e: SecurityException) {
            Log.e("ocean", "❌ Security exception while deleting: ${e.message}")
            DeleteResult.failure(PRApp.getStringRes(R.string.error_permission_delete_file))
        } catch (e: Exception) {
            Log.e("ocean", "❌ Exception while deleting file: ${e.message}")
            DeleteResult.failure(
                PRApp.getStringRes(
                    R.string.error_file_delete_failed,
                    e.message.toString()
                )
            )
        }
    }

    /**
     * 删除文件（异步版本）- 功能完善的删除方法
     *
     * @param file 要删除的文件
     * @param deleteEmptyParentDirs 是否删除空的父目录（默认false）
     * @param dryRun 是否只模拟删除不实际执行（默认false）
     * @return DeleteResult对象，包含删除结果和详细信息
     */
    suspend fun deleteFileAsync(
        file: File,
        deleteEmptyParentDirs: Boolean = false,
        dryRun: Boolean = false
    ): DeleteResult =
        withContext(Dispatchers.IO) {
            deleteFile(file, deleteEmptyParentDirs, dryRun)
        }

    /**
     * 批量删除文件
     *
     * @param files 要删除的文件列表
     * @param deleteEmptyParentDirs 是否删除空的父目录（默认false）
     * @param dryRun 是否只模拟删除不实际执行（默认false）
     * @return DeleteResult对象，包含总体删除结果
     */
    fun deleteFiles(
        files: List<File>,
        deleteEmptyParentDirs: Boolean = false,
        dryRun: Boolean = false
    ): DeleteResult {
        if (files.isEmpty()) {
            return DeleteResult.success(0, 0)
        }

        var totalDeleted = 0
        var totalSize = 0L
        val errors = mutableListOf<String>()

        files.forEach { file ->
            val result = deleteFile(file, deleteEmptyParentDirs, dryRun)
            if (result.success) {
                totalDeleted += result.deletedFiles
                totalSize += result.deletedSize
            } else {
                errors.add("${file.name}: ${result.errorMessage}")
            }
        }

        return if (errors.isEmpty()) {
            DeleteResult.success(totalDeleted, totalSize)
        } else {
            val error = "\n${errors.joinToString("\n")}"
            DeleteResult.failure(PRApp.getStringRes(R.string.error_some_files_not_deleted, error))
        }
    }

    /**
     * 删除目录及其所有内容（递归删除）
     *
     * @param directory 要删除的目录
     * @param dryRun 是否只模拟删除不实际执行（默认false）
     * @return DeleteResult对象，包含删除结果
     */
    fun deleteDirectoryRecursive(directory: File, dryRun: Boolean = false): DeleteResult {
        if (!directory.exists()) {
            return DeleteResult.failure(PRApp.getStringRes(R.string.error_directory_does_not_exist))
        }

        if (!directory.isDirectory) {
            return DeleteResult.failure(PRApp.getStringRes(R.string.error_path_not_directory))
        }

        if (isProtectedPath(directory)) {
            return DeleteResult.failure(PRApp.getStringRes(R.string.error_cannot_delete_protected_directory))
        }

        var deletedCount = 0
        var deletedSize = 0L

        // 先删除目录下的所有文件和子目录
        directory.listFiles()?.forEach { file ->
            val result = if (file.isDirectory) {
                deleteDirectoryRecursive(file, dryRun)
            } else {
                deleteFile(file, false, dryRun)
            }

            if (result.success) {
                deletedCount += result.deletedFiles
                deletedSize += result.deletedSize
            }
        }

        // 最后删除空目录本身
        val dirResult = deleteFile(directory, false, dryRun)
        if (dirResult.success) {
            deletedCount += 1
        }

        return DeleteResult.success(deletedCount, deletedSize)
    }

    /**
     * 检查是否为受保护的路径（防止误删系统文件）
     */
    private fun isProtectedPath(file: File): Boolean {
        val protectedPaths = listOf(
            "/system",
            "/data",
            "/vendor",
            "/sbin",
            "/etc",
            "/dev",
            "/proc",
            "/sys",
            "/root",
            "/acct",
            "/mnt",
            "/storage/emulated/0/Android",
            "/storage/emulated/0/.android_secure"
        )

        val absolutePath = file.absolutePath
        return protectedPaths.any { protectedPath ->
            absolutePath.startsWith(protectedPath)
        }
    }

    /**
     * 删除空的父目录（向上递归）
     */
    private fun deleteEmptyParentDirectories(directory: File?) {
        directory?.let { dir ->
            if (dir.exists() && dir.isDirectory && dir.listFiles()?.isEmpty() == true) {
                val parent = dir.parentFile
                if (dir.delete()) {
                    Log.d("ocean", "✅ Deleted empty parent directory: ${dir.path}")
                    deleteEmptyParentDirectories(parent)
                }
            }
        }
    }

    /**
     * 安全删除文件到回收站（如果系统支持）
     *
     * @param context 上下文
     * @param file 要删除的文件
     * @return DeleteResult对象
     */
    fun moveToTrash(context: Context, file: File): DeleteResult {
        return try {
            // Android 10+ 支持系统回收站
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                MediaStore.createTrashRequest(
                    context.contentResolver,
                    listOf(Uri.fromFile(file)),
                    true
                )
                // 注意：这里需要Activity来启动IntentSender
                DeleteResult.success(1, file.length())
            } else {
                // 低版本直接删除
                deleteFile(file)
            }
        } catch (e: Exception) {
            DeleteResult.failure("Failed to move file to trash: ${e.message}")
        }
    }
}