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

import Foundation
@preconcurrency import ImageCaptureCore

/// 索尼相机 **MTP 历史导入** 路径的 Driver 实现。
/// PC Remote 边拍边传由 `SonyRemoteCaptureService` + PTP 负责，与本 Driver 的 catalog 扫描分离。
/// 索尼在 PC Remote 模式下 catalog 常为空，需提示用户切换 MTP（见 AGENTS.md）。
final class SonyCameraDriver: CameraDriver {
    private let device: ICCameraDevice
    let platform: CameraPlatform = .sony
    let deviceInfo: CameraDeviceInfo

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

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

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

    /// 扫描 `mediaFiles` / `contents` 树；PC Remote 模式下可能返回空列表。
    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(.sony, "listObjects: mediaFiles=\(mediaFilesCount), contents=\(contentsCount), images=\(files.count)")

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

        OTGLog.info(.sony, "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(.sony, "downloadObject file not found: \(object.filename)")
            throw CameraError.deviceNotFound
        }

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