import CoreGraphics
import Foundation
import ImageCaptureCore

/// ImageCaptureCore 文件下载回调代理。
final class CameraDownloadDelegate: NSObject, ICCameraDeviceDownloadDelegate {
    var onComplete: ((ICCameraFile, URL?, Error?) -> Void)?
    var onProgress: ((String, Double) -> Void)?

    @objc func didDownloadFile(_ file: ICCameraFile, error: Error?, options: [String: Any], contextInfo: UnsafeMutableRawPointer?) {
        if let error {
            CameraTetheringLogger.log("下载失败 \(file.name ?? "?"): \(error.localizedDescription)", logger: CameraTetheringLogger.transfer)
            onComplete?(file, nil, error)
            return
        }

        let downloadOptions = options as? [ICDownloadOption: Any] ?? [:]
        if let directory = downloadOptions[.downloadsDirectoryURL] as? URL,
           let filename = downloadOptions[.savedFilename] as? String {
            let url = directory.appendingPathComponent(filename)
            CameraTetheringLogger.log("下载完成 \(filename) -> \(url.path)", logger: CameraTetheringLogger.transfer)
            onComplete?(file, url, nil)
        } else if let urlString = file.value(forKey: "url") as? String {
            let url = URL(fileURLWithPath: urlString)
            CameraTetheringLogger.log("下载完成 \(file.name ?? "?") -> \(url.path)", logger: CameraTetheringLogger.transfer)
            onComplete?(file, url, nil)
        } else {
            CameraTetheringLogger.log("下载完成但无法定位路径: \(file.name ?? "?")", logger: CameraTetheringLogger.transfer)
            onComplete?(file, nil, CameraServiceError.downloadFailed("无法定位下载文件路径"))
        }
    }

    @objc func didReceiveDownloadProgress(for file: ICCameraFile, downloadedBytes: off_t, maxBytes: off_t) {
        guard maxBytes > 0, let name = file.name else { return }
        onProgress?(name, Double(downloadedBytes) / Double(maxBytes))
    }
}
