package com.example.initiateaphonecallapp.util

import com.example.initiateaphonecallapp.data.model.SearchResult
import com.example.initiateaphonecallapp.data.model.SearchState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

class FileSearcher {

    private val possibleDirs = listOf(
        File("/storage/emulated/0/MIUI/sound_recorder/call_rec/"), // 小米
        File("/storage/emulated/0/Record/call/"),                  // 华为
        File("/storage/emulated/0/Sounds/CallRecord/"),            // 其他华为机型
        File("/storage/emulated/0/AudioRecord/")                   // 其他华为机型
    )

    suspend fun searchFiles(
        fileExtensions: List<String> = listOf(".mp3", ".m4a", ".aac", ".wav", ".amr"),
        maxDepth: Int = 10
    ): SearchState = withContext(Dispatchers.IO) {
        try {
            val results = mutableListOf<SearchResult>()
            val searchedDirs = mutableListOf<String>()

            possibleDirs.forEach { dir ->
                if (dir.exists() && dir.isDirectory) {
                    searchedDirs.add(dir.absolutePath)
                    searchInDirectory(dir, fileExtensions, maxDepth, results)
                }
            }

            SearchState(
                isSearching = false,
                results = results,
                searchedDirectories = searchedDirs
            )
        } catch (e: Exception) {
            SearchState(
                isSearching = false,
                errorMessage = "搜索失败: ${e.message}"
            )
        }
    }

    private fun searchInDirectory(
        directory: File,
        extensions: List<String>,
        maxDepth: Int,
        results: MutableList<SearchResult>,
        currentDepth: Int = 0
    ) {
        if (currentDepth > maxDepth) return

        try {
            val files = directory.listFiles() ?: return

            files.forEach { file ->
                if (file.isDirectory) {
                    // 递归搜索子目录
                    searchInDirectory(file, extensions, maxDepth, results, currentDepth + 1)
                } else {
                    // 检查文件扩展名
                    val fileExtension = file.extension.lowercase()
                    if (extensions.any { it.lowercase() == ".$fileExtension" }) {
                        results.add(
                            SearchResult(
                                file = file,
                                directory = file.parent ?: "",
                                fileName = file.name,
                                fileSize = file.length(),
                                lastModified = file.lastModified()
                            )
                        )
                    }
                }
            }
        } catch (e: SecurityException) {
            // 处理权限问题
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 可选：搜索特定文件名模式
    suspend fun searchFilesWithPattern(
        pattern: String,
        fileExtensions: List<String> = listOf(".mp3", ".m4a", ".aac", ".wav", ".amr")
    ): SearchState = withContext(Dispatchers.IO) {
        try {
            val results = mutableListOf<SearchResult>()
            val searchedDirs = mutableListOf<String>()

            possibleDirs.forEach { dir ->
                if (dir.exists() && dir.isDirectory) {
                    searchedDirs.add(dir.absolutePath)
                    searchInDirectoryWithPattern(dir, pattern, fileExtensions, results)
                }
            }

            SearchState(
                isSearching = false,
                results = results,
                searchedDirectories = searchedDirs
            )
        } catch (e: Exception) {
            SearchState(
                isSearching = false,
                errorMessage = "搜索失败: ${e.message}"
            )
        }
    }

    private fun searchInDirectoryWithPattern(
        directory: File,
        pattern: String,
        extensions: List<String>,
        results: MutableList<SearchResult>
    ) {
        try {
            val files = directory.listFiles() ?: return

            files.forEach { file ->
                if (file.isDirectory) {
                    searchInDirectoryWithPattern(file, pattern, extensions, results)
                } else {
                    val fileExtension = file.extension.lowercase()
                    val fileName = file.name.lowercase()
                    val searchPattern = pattern.lowercase()

                    if ((extensions.isEmpty() || extensions.any { it.lowercase() == ".$fileExtension" }) &&
                        fileName.contains(searchPattern)) {
                        results.add(
                            SearchResult(
                                file = file,
                                directory = file.parent ?: "",
                                fileName = file.name,
                                fileSize = file.length(),
                                lastModified = file.lastModified()
                            )
                        )
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}