import Foundation
import ImageCaptureCore

@MainActor
final class SonyCameraService: CameraServiceProtocol {
    let brand: CameraBrand = .sony

    private(set) var connectionState: CameraConnectionState = .disconnected
    var onConnectionStateChange: ((CameraConnectionState) -> Void)?
    var onNewAsset: ((CameraAsset) -> Void)?

    private let deviceManager = ImageCaptureDeviceManager()
    private var knownAssetIDs: Set<String> = []
    private var baselineEstablished = false
    private var pendingAssetsWhileDetached: [CameraAsset] = []

    init() {
        deviceManager.onConnectionStateChange = { [weak self] state in
            Task { @MainActor in
                self?.connectionState = state
                self?.onConnectionStateChange?(state)
            }
        }

        deviceManager.onNewItems = { [weak self] items in
            Task { @MainActor in
                self?.handleNewItems(items, source: "didAddItems")
            }
        }

        deviceManager.onBaselineCatalogReady = { [weak self] in
            Task { @MainActor in
                self?.establishBaseline()
            }
        }

        deviceManager.onPollTick = { [weak self] in
            Task { @MainActor in
                self?.scanForNewAssets(source: "poll")
            }
        }

        deviceManager.onPTPAssetReady = { [weak self] asset, _ in
            Task { @MainActor in
                self?.handlePTPAsset(asset)
            }
        }

        deviceManager.onError = { [weak self] message in
            Task { @MainActor in
                CameraTetheringLogger.log("相机错误: \(message)")
                self?.connectionState = .error(message)
                self?.onConnectionStateChange?(.error(message))
            }
        }
    }

    func connect() async {
        CameraTetheringLogger.log("SonyCameraService.connect()")
        let shouldResetBaseline = !deviceManager.isBrowsing
        deviceManager.startBrowsing()
        if shouldResetBaseline {
            knownAssetIDs.removeAll()
            baselineEstablished = false
        }
    }

    /// 由 AutoDetect 在已完成授权后直接挂载设备。
    func attach(to camera: ICCameraDevice) async {
        CameraTetheringLogger.log("SonyCameraService.attach()")
        knownAssetIDs.removeAll()
        baselineEstablished = false
        pendingAssetsWhileDetached.removeAll()
        deviceManager.attach(to: camera)
    }

    /// 页面离开：仅清空 UI 回调，底层 PTP 会话与轮询继续。
    func detachFromUI() {
        CameraTetheringLogger.log("SonyCameraService.detachFromUI()")
        onConnectionStateChange = nil
        onNewAsset = nil
    }

    /// 再次进入页面：补发 detach 期间缓冲的新照片。
    func reattachToUI() {
        guard !pendingAssetsWhileDetached.isEmpty else { return }
        let pending = pendingAssetsWhileDetached
        pendingAssetsWhileDetached.removeAll()
        CameraTetheringLogger.log("SonyCameraService.reattachToUI: 补发 \(pending.count) 张离线新片")
        for asset in pending {
            onNewAsset?(asset)
        }
    }

    func shutdown() async {
        CameraTetheringLogger.log("SonyCameraService.shutdown()")
        await deviceManager.stopBrowsing()
        knownAssetIDs.removeAll()
        baselineEstablished = false
        pendingAssetsWhileDetached.removeAll()
        connectionState = .disconnected
        onConnectionStateChange?(.disconnected)
    }

    func listAssets() async throws -> [CameraAsset] {
        guard connectionState.isConnected else {
            throw CameraServiceError.notConnected
        }
        let assets = deviceManager.allFiles().map { deviceManager.makeAsset(from: $0) }
        CameraTetheringLogger.log("listAssets: \(assets.count) 个文件")
        return assets
    }

    func downloadAsset(_ asset: CameraAsset) async throws -> URL {
        guard connectionState.isConnected else {
            throw CameraServiceError.notConnected
        }
        if let cachedURL = deviceManager.localURL(forAssetID: asset.id) {
            CameraTetheringLogger.log("downloadAsset: 返回 PTP 缓存 \(asset.filename)", logger: CameraTetheringLogger.transfer)
            return cachedURL
        }
        guard let file = deviceManager.file(forAssetID: asset.id) else {
            CameraTetheringLogger.log("downloadAsset: 找不到文件 \(asset.filename) id=\(asset.id)", logger: CameraTetheringLogger.transfer)
            throw CameraServiceError.assetNotFound
        }

        let directory = CameraDownloadStorage.temporaryDownloadsDirectory
        return try await deviceManager.download(file: file, to: directory)
    }

    private func handlePTPAsset(_ asset: CameraAsset) {
        deliverNewAsset(asset, source: "PTP")
    }

    /// 连接后首次目录就绪：已有照片记入基线；拍摄于枚举期间的新照片立即传输。
    private func establishBaseline() {
        guard !baselineEstablished else { return }
        baselineEstablished = true

        let files = deviceManager.allFiles()
        var skipped = 0
        var newCount = 0

        for file in files {
            if file.wasAddedAfterContentCatalogCompleted {
                emitAssetIfNew(file: file, source: "baseline-new")
                newCount += 1
            } else {
                knownAssetIDs.insert(deviceManager.assetIdentifier(for: file))
                skipped += 1
            }
        }
        CameraTetheringLogger.log("基线已建立: 跳过已有 \(skipped) 张, 立即传输新拍 \(newCount) 张")
    }

    private func handleNewItems(_ items: [ICCameraItem], source: String) {
        guard baselineEstablished else {
            CameraTetheringLogger.log("\(source): 基线未建立，暂存处理")
            return
        }

        for item in items {
            guard let file = item as? ICCameraFile else { continue }
            emitAssetIfNew(file: file, source: source)
        }
    }

    private func scanForNewAssets(source: String) {
        guard baselineEstablished else { return }

        let files = deviceManager.allFiles()
        for file in files {
            emitAssetIfNew(file: file, source: source)
        }
    }

    private func emitAssetIfNew(file: ICCameraFile, source: String) {
        let asset = deviceManager.makeAsset(from: file)
        deliverNewAsset(asset, source: source)
    }

    private func deliverNewAsset(_ asset: CameraAsset, source: String) {
        guard !knownAssetIDs.contains(asset.id) else { return }
        knownAssetIDs.insert(asset.id)
        CameraTetheringLogger.log(
            "[\(source)] 发现新照片: \(asset.filename) id=\(asset.id) size=\(asset.fileSize)",
            logger: CameraTetheringLogger.transfer
        )
        if let onNewAsset {
            onNewAsset(asset)
        } else {
            pendingAssetsWhileDetached.append(asset)
        }
    }
}
