//
//  ICCameraFileDownloader.swift
//  otg_swift
//

import Foundation
@preconcurrency import ImageCaptureCore

/// 封装 `ICCameraFile.requestDownload`，将相机文件异步保存到本地目录。
enum ICCameraFileDownloader {

    /// 下载到 `directory`，同名文件自动追加序号，避免覆盖已导入原片。
    static func download(_ file: ICCameraFile, to directory: URL) async throws -> URL {
        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)

        let filename = uniqueFilename(file.name ?? UUID().uuidString, in: directory)
        let destinationURL = directory.appendingPathComponent(filename)

        if FileManager.default.fileExists(atPath: destinationURL.path) {
            try FileManager.default.removeItem(at: destinationURL)
        }

        return try await withCheckedThrowingContinuation { continuation in
            let options: [ICDownloadOption: Any] = [
                .downloadsDirectoryURL: directory,
                .savedFilename: filename,
                .overwrite: true
            ]

            file.requestDownload(options: options) { savedFilename, error in
                if let error {
                    continuation.resume(throwing: error)
                    return
                }

                let resolvedFilename = savedFilename ?? filename
                let resolvedURL = directory.appendingPathComponent(resolvedFilename)
                guard FileManager.default.fileExists(atPath: resolvedURL.path) else {
                    continuation.resume(throwing: CameraError.connectionFailed("下载文件未找到"))
                    return
                }
                continuation.resume(returning: resolvedURL)
            }
        }
    }

    private static func uniqueFilename(_ rawName: String, in directory: URL) -> String {
        let sanitized = PTPHelper.sanitizeFilename(rawName)
        let baseURL = directory.appendingPathComponent(sanitized)
        if !FileManager.default.fileExists(atPath: baseURL.path) {
            return sanitized
        }

        let stem = (sanitized as NSString).deletingPathExtension
        let ext = (sanitized as NSString).pathExtension
        var counter = 1
        while counter < 10_000 {
            let candidate = ext.isEmpty ? "\(stem)_\(counter)" : "\(stem)_\(counter).\(ext)"
            if !FileManager.default.fileExists(atPath: directory.appendingPathComponent(candidate).path) {
                return candidate
            }
            counter += 1
        }
        return "\(UUID().uuidString)_\(sanitized)"
    }
}
