// utils/CallRecordScanner.kt
package com.example.initiateaphonecallapp.utils

import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import java.text.SimpleDateFormat
import java.util.*

object CallRecordScanner {
    private const val TAG = "CallRecordScanner"

    // 支持的录音目录路径和对应的品牌
    private val recordDirs = mapOf(
        "/MIUI/sound_recorder/call_rec/" to "小米",
        "/Record/call/" to "华为",
        "/Sounds/CallRecord/" to "华为其他机型",
        "/AudioRecord/" to "其他机型"
    )

    data class CallRecordFile(
        val id: Long,
        val displayName: String,
        val filePath: String,
        val size: Long,
        val dateModified: Long,
        val uri: Uri,
        val phoneNumber: String?,
        val timestamp: String?,
        val brand: String,
        val directory: String
    )

    /**
     * 扫描所有通话录音文件（不限制文件名格式）
     */
    fun scanAllCallRecords(context: Context): List<CallRecordFile> {
        val callRecords = mutableListOf<CallRecordFile>()

        try {
            val projection = arrayOf(
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Audio.Media.SIZE,
                MediaStore.Audio.Media.DATE_MODIFIED,
                MediaStore.Audio.Media.DATA
            )

            // 只根据路径查询，不限制文件名格式
            val selection = buildPathSelectionQuery()
            val selectionArgs = buildPathSelectionArgs()

            val sortOrder = "${MediaStore.Audio.Media.DATE_MODIFIED} DESC"

            Log.d(TAG, "开始扫描所有通话录音文件...")
            Log.d(TAG, "查询条件: $selection")
            Log.d(TAG, "查询参数: ${selectionArgs.joinToString()}")
            Log.d(TAG, "支持的目录:")
            recordDirs.forEach { (path, brand) ->
                Log.d(TAG, "  $brand: $path")
            }

            context.contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                sortOrder
            )?.use { cursor ->
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
                val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)
                val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)
                val dateModifiedColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_MODIFIED)
                val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)

                var foundCount = 0
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idColumn)
                    val name = cursor.getString(nameColumn)
                    val size = cursor.getLong(sizeColumn)
                    val dateModified = cursor.getLong(dateModifiedColumn)
                    val filePath = cursor.getString(dataColumn)

                    // 解析文件名获取手机号（宽松匹配）
                    val phoneNumber = extractPhoneNumberFromFileName(name)

                    // 获取品牌和目录信息
                    val (brand, directory) = getBrandAndDirectory(filePath)

                    val uri = ContentUris.withAppendedId(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        id
                    )

                    callRecords.add(
                        CallRecordFile(
                            id = id,
                            displayName = name,
                            filePath = filePath,
                            size = size,
                            dateModified = dateModified,
                            uri = uri,
                            phoneNumber = phoneNumber,
                            timestamp = extractTimestampFromFileName(name),
                            brand = brand,
                            directory = directory
                        )
                    )

                    foundCount++
                    Log.d(TAG, "找到通话录音 [$foundCount]:")
                    Log.d(TAG, "  文件名: $name")
                    Log.d(TAG, "  路径: $filePath")
                    Log.d(TAG, "  品牌: $brand")
                    Log.d(TAG, "  目录: $directory")
                    Log.d(TAG, "  解析手机号: $phoneNumber")
                    Log.d(TAG, "  大小: ${formatFileSize(size)}")
                    Log.d(TAG, "  修改时间: ${formatDate(dateModified * 1000)}")
                }

                Log.d(TAG, "扫描完成，找到 $foundCount 个通话录音文件")
            }

        } catch (e: Exception) {
            Log.e(TAG, "扫描通话录音失败: ${e.message}", e)
        }

        return callRecords
    }

    /**
     * 根据手机号前缀查找匹配的通话录音文件
     */
    fun findCallRecordsByPhonePrefix(context: Context, phonePrefix: String): List<CallRecordFile> {
        val allRecords = scanAllCallRecords(context)
        return allRecords.filter { record ->
            // 宽松匹配：只要文件名以手机号前缀开头就匹配
            record.phoneNumber?.startsWith(phonePrefix) == true ||
                    // 或者文件名包含手机号前缀
                    record.displayName.contains(phonePrefix) ||
                    // 或者解析出的手机号包含前缀
                    (record.phoneNumber != null && record.phoneNumber.contains(phonePrefix))
        }.sortedByDescending { it.dateModified }
    }

    /**
     * 根据完整手机号查找最新的通话录音文件
     */
    fun findLatestCallRecordByPhone(context: Context, phoneNumber: String): CallRecordFile? {
        val allRecords = scanAllCallRecords(context)
        return allRecords
            .filter { record ->
                // 多种匹配方式
                record.phoneNumber == phoneNumber ||
                        record.displayName.startsWith("${phoneNumber}_") ||
                        record.displayName.startsWith(phoneNumber) ||
                        (record.phoneNumber != null && record.phoneNumber.endsWith(phoneNumber)) ||
                        (record.phoneNumber != null && phoneNumber.endsWith(record.phoneNumber))
            }
            .maxByOrNull { it.dateModified }
    }

    /**
     * 从文件名中提取手机号（宽松匹配）
     */
    /**
     * 从文件名中提取手机号（支持多种格式）
     */
    private fun extractPhoneNumberFromFileName(fileName: String): String? {
        return try {
            // 移除文件扩展名
            val nameWithoutExt = fileName.removeSuffix(".mp3")
                .removeSuffix(".MP3")
                .removeSuffix(".m4a")
                .removeSuffix(".M4A")
                .removeSuffix(".amr")
                .removeSuffix(".AMR")
                .removeSuffix(".wav")
                .removeSuffix(".WAV")

            Log.d(TAG, "解析文件名: $nameWithoutExt")

            // 模式1: 手机号(手机号)_时间戳 格式 - 处理 18061119371(18061119371)_2025111762138
            val pattern1 = Regex("""^(\d+)\(\1\)_(\d+)$""")
            pattern1.find(nameWithoutExt)?.let { match ->
                val phoneNumber = match.groupValues[1]
                if (phoneNumber.length in 7..15) {
                    Log.d(TAG, "模式1匹配: 手机号=$phoneNumber")
                    return phoneNumber
                }
            }

            // 模式2: 手机号(另一个手机号)_时间戳 格式
            val pattern2 = Regex("""^(\d+)\((\d+)\)_(\d+)$""")
            pattern2.find(nameWithoutExt)?.let { match ->
                val phoneNumber1 = match.groupValues[1]
                val phoneNumber2 = match.groupValues[2]
                // 优先使用第一个手机号
                if (phoneNumber1.length in 7..15) {
                    Log.d(TAG, "模式2匹配: 手机号1=$phoneNumber1, 手机号2=$phoneNumber2")
                    return phoneNumber1
                } else if (phoneNumber2.length in 7..15) {
                    Log.d(TAG, "模式2匹配: 使用手机号2=$phoneNumber2")
                    return phoneNumber2
                }
            }

            // 模式3: 手机号_时间戳 格式
            val pattern3 = Regex("""^(\d+)_(\d+)$""")
            pattern3.find(nameWithoutExt)?.let { match ->
                val phoneNumber = match.groupValues[1]
                if (phoneNumber.length in 7..15) {
                    Log.d(TAG, "模式3匹配: 手机号=$phoneNumber")
                    return phoneNumber
                }
            }

            // 模式4: 纯数字文件名（可能是手机号）
            if (nameWithoutExt.all { it.isDigit() } && nameWithoutExt.length in 7..15) {
                Log.d(TAG, "模式4匹配: 纯数字手机号=$nameWithoutExt")
                return nameWithoutExt
            }

            // 模式5: 从文件名开头提取连续数字
            val pattern5 = Regex("""^(\d+)""")
            pattern5.find(nameWithoutExt)?.let { match ->
                val digits = match.value
                if (digits.length in 7..15) {
                    Log.d(TAG, "模式5匹配: 开头数字=$digits")
                    return digits
                }
            }

            // 模式6: 从任意位置提取看起来像手机号的数字序列
            val phonePattern = Regex("""\d{7,15}""")
            val allMatches = phonePattern.findAll(nameWithoutExt).toList()

            if (allMatches.isNotEmpty()) {
                // 优先选择长度11位的（标准手机号长度）
                val standardPhone = allMatches.find { it.value.length == 11 }
                if (standardPhone != null) {
                    Log.d(TAG, "模式6匹配: 标准11位手机号=${standardPhone.value}")
                    return standardPhone.value
                }

                // 否则选择第一个匹配的
                val firstMatch = allMatches.first()
                Log.d(TAG, "模式6匹配: 第一个数字序列=${firstMatch.value}")
                return firstMatch.value
            }

            Log.d(TAG, "未找到匹配的手机号格式")
            null

        } catch (e: Exception) {
            Log.w(TAG, "提取手机号失败: $fileName, ${e.message}")
            null
        }
    }

    /**
     * 从文件名中提取时间戳（如果有的话）
     */
    /**
     * 从文件名中提取时间戳（支持多种格式）
     */
    private fun extractTimestampFromFileName(fileName: String): String? {
        return try {
            val nameWithoutExt = fileName.removeSuffix(".mp3")
                .removeSuffix(".MP3")
                .removeSuffix(".m4a")
                .removeSuffix(".M4A")
                .removeSuffix(".amr")
                .removeSuffix(".AMR")
                .removeSuffix(".wav")
                .removeSuffix(".WAV")

            Log.d(TAG, "提取时间戳 from: $nameWithoutExt")

            // 匹配13位或14位数字时间戳（通常在文件名末尾）
            val timestampPattern = Regex("""_(\d{13,14})$""")
            timestampPattern.find(nameWithoutExt)?.let { match ->
                val timestamp = match.groupValues[1]
                Log.d(TAG, "找到时间戳: $timestamp")
                return timestamp
            }

            // 如果没有下划线前缀，尝试匹配末尾的13-14位数字
            val endTimestampPattern = Regex("""(\d{13,14})$""")
            endTimestampPattern.find(nameWithoutExt)?.let { match ->
                val timestamp = match.value
                Log.d(TAG, "找到末尾时间戳: $timestamp")
                return timestamp
            }

            Log.d(TAG, "未找到时间戳")
            null

        } catch (e: Exception) {
            Log.w(TAG, "提取时间戳失败: $fileName, ${e.message}")
            null
        }
    }

    /**
     * 构建路径查询条件（不限制文件名格式）
     */
    private fun buildPathSelectionQuery(): String {
        return recordDirs.keys.map {
            "${MediaStore.Audio.Media.DATA} LIKE ?"
        }.joinToString(" OR ")
    }

    private fun buildPathSelectionArgs(): Array<String> {
        return recordDirs.keys.map { "%$it%" }.toTypedArray()
    }

    /**
     * 根据文件路径获取品牌和目录信息
     */
    private fun getBrandAndDirectory(filePath: String): Pair<String, String> {
        for ((path, brand) in recordDirs) {
            if (filePath.contains(path)) {
                return brand to path
            }
        }
        return "未知" to "其他目录"
    }

    /**
     * 获取查询路径信息（用于显示）
     */
    fun getQueryPaths(): List<Pair<String, String>> {
        return recordDirs.map { (path, brand) ->
            brand to path
        }
    }

    /**
     * 获取所有支持的目录
     */
    fun getSupportedDirectories(): Map<String, String> {
        return recordDirs
    }

    /**
     * 检查是否有可访问的录音目录
     */
    fun hasAccessibleRecordDirs(): Boolean {
        return recordDirs.isNotEmpty()
    }

    // 格式化文件大小
    private fun formatFileSize(size: Long): String {
        return when {
            size < 1024 -> "$size B"
            size < 1024 * 1024 -> "${size / 1024} KB"
            else -> "${size / (1024 * 1024)} MB"
        }
    }

    // 格式化日期
    private fun formatDate(timestamp: Long): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(Date(timestamp))
    }

    /**
     * 格式化时间戳为可读格式
     */
    fun formatTimestamp(timestamp: String): String {
        return try {
            if (timestamp.length == 14) {
                val sdf = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
                val date = sdf.parse(timestamp)
                SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(date)
            } else {
                timestamp
            }
        } catch (e: Exception) {
            timestamp
        }
    }
}