//
//  CanonCameraDriver.swift
//  otg_swift
//
//  Created by hanqiu on 2026/7/2.
//

import Foundation
@preconcurrency import ImageCaptureCore

/// 佳能相机 Driver：ImageCaptureCore 枚举 SD 卡历史照片并下载。
/// 边拍边传由 `CanonRemoteCaptureService` + EOS GetEvent 负责，与 catalog 扫描分离。
final class CanonCameraDriver: CameraDriver {
    private let device: ICCameraDevice
    let platform: CameraPlatform = .canon
    let deviceInfo: CameraDeviceInfo

    init(device: ICCameraDevice, deviceInfo: CameraDeviceInfo) {
        self.device = device
        self.deviceInfo = deviceInfo
        OTGLog.info(.canon, "initialized, device=\(deviceInfo.name)")
    }

    func connect() async throws {
        OTGLog.debug(.canon, "connect called")
    }

    func disconnect() {
        OTGLog.info(.canon, "driver released, device=\(deviceInfo.name)")
    }

    func listObjects() async throws -> [CameraObject] {
        let mediaFilesCount = device.mediaFiles?.count ?? 0
        let contentsCount = device.contents?.count ?? 0
        let files = ICCameraItemScanner.collectImageFiles(from: device)
        OTGLog.info(.canon, "listObjects: mediaFiles=\(mediaFilesCount), contents=\(contentsCount), images=\(files.count)")

        let results = await ICCameraItemScanner.cameraObjects(from: files)
            .sorted { $0.capturedAt > $1.capturedAt }

        OTGLog.info(.canon, "listObjects: image count=\(results.count)")
        return results
    }

    func requestThumbnailData(for object: CameraObject, maxPixelSize: Int) async -> Data? {
        await ICCameraThumbnailLoader.loadThumbnailData(for: object, from: device, maxPixelSize: maxPixelSize)
    }

    func downloadObject(_ object: CameraObject, to directory: URL) async throws -> URL {
        guard let file = ICCameraItemScanner.findFile(matching: object, in: device) else {
            OTGLog.error(.canon, "downloadObject file not found: \(object.filename)")
            throw CameraError.deviceNotFound
        }

        let url = try await ICCameraFileDownloader.download(file, to: directory)
        OTGLog.info(.canon, "downloadObject saved: \(url.lastPathComponent)")
        return url
    }
}
