//
//  ICCameraDevice+DebugLog.swift
//  otg_swift
//

import CoreGraphics
@preconcurrency import ImageCaptureCore

/// 调试工具：打印 ICCameraDevice 非空属性，辅助 PlatformDetector 与 catalog 为空问题排查。
enum ICCameraDeviceDebugLogger {

    /// 打印 ICCameraDevice 在 iOS 上可访问的非空属性，便于调试 PlatformDetector 与连接问题。
    static func logNonEmptyProperties(of camera: ICCameraDevice, context: String) {
        var lines: [String] = []
        lines.append("=== ICCameraDevice [\(context)] ===")

        // MARK: ICDevice
        append("type", String(describing: camera.type.rawValue), to: &lines)
        append("name", camera.name, to: &lines)
        append("productKind", camera.productKind, to: &lines)
        append("transportType", camera.transportType, to: &lines)
        append("uuidString", camera.uuidString, to: &lines)
        append("systemSymbolName", camera.systemSymbolName, to: &lines)

        appendIfTrue("hasOpenSession", camera.hasOpenSession, to: &lines)
        appendCapabilities(camera.capabilities, to: &lines)
        appendUserData(camera.userData, to: &lines)
        appendIcon(camera.icon, to: &lines)

        appendUSBID("usbVendorID", Int(camera.usbVendorID), to: &lines)
        appendUSBID("usbProductID", Int(camera.usbProductID), to: &lines)
        appendUSBID("usbLocationID", Int(camera.usbLocationID), to: &lines)

        // MARK: ICCameraDevice
        if camera.contentCatalogPercentCompleted > 0 {
            lines.append("contentCatalogPercentCompleted=\(camera.contentCatalogPercentCompleted)")
        }

        appendItems("contents", camera.contents, to: &lines)
        appendItems("mediaFiles", camera.mediaFiles, to: &lines)

        appendIfTrue("ejectable", camera.isEjectable, to: &lines)
        appendIfTrue("locked", camera.isLocked, to: &lines)
        appendIfTrue("accessRestrictedAppleDevice", camera.isAccessRestrictedAppleDevice, to: &lines)
        appendIfTrue("iCloudPhotosEnabled", camera.iCloudPhotosEnabled, to: &lines)
        appendIfTrue("tetheredCaptureEnabled", camera.tetheredCaptureEnabled, to: &lines)

        if #available(iOS 14.0, *) {
            lines.append("mediaPresentation=\(camera.mediaPresentation.rawValue)")
        }

        if camera.batteryLevelAvailable {
            lines.append("batteryLevelAvailable=true")
            lines.append("batteryLevel=\(camera.batteryLevel)")
        }

        lines.append("ptpEventHandler=set")

        lines.append("=== end ICCameraDevice dump ===")

        for line in lines {
            OTGLog.debug(.connection, line)
        }
    }

    // MARK: - Helpers

    private static func append(_ key: String, _ value: String?, to lines: inout [String]) {
        guard let value, !value.isEmpty else { return }
        lines.append("\(key)=\(value)")
    }

    private static func appendIfTrue(_ key: String, _ value: Bool, to lines: inout [String]) {
        guard value else { return }
        lines.append("\(key)=true")
    }

    private static func appendUSBID(_ key: String, _ value: Int, to lines: inout [String]) {
        guard value != 0 else { return }
        lines.append("\(key)=0x\(String(format: "%04X", value)) (\(value))")
    }

    private static func appendCapabilities(_ capabilities: [String], to lines: inout [String]) {
        guard !capabilities.isEmpty else { return }
        lines.append("capabilities=[\(capabilities.joined(separator: ", "))]")
    }

    private static func appendUserData(_ userData: NSMutableDictionary?, to lines: inout [String]) {
        guard let userData, !userData.allKeys.isEmpty else { return }
        lines.append("userData=\(userData)")
    }

    private static func appendIcon(_ icon: CGImage?, to lines: inout [String]) {
        guard let icon else { return }
        lines.append("icon=present(\(icon.width)x\(icon.height))")
    }

    private static func appendItems(_ key: String, _ items: [ICCameraItem]?, to lines: inout [String]) {
        guard let items, !items.isEmpty else { return }
        let names = items.prefix(5).map { $0.name ?? "unnamed" }.joined(separator: ", ")
        let suffix = items.count > 5 ? ", ..." : ""
        lines.append("\(key).count=\(items.count)")
        lines.append("\(key).preview=[\(names)\(suffix)]")
    }
}
