//
//  PlatformDetector.swift
//  otg_swift
//

import Foundation

/// 根据 USB Vendor ID 与设备名字符串识别相机品牌。
enum PlatformDetector {

    private struct Rule {
        let platform: CameraPlatform
        let keywords: [String]
    }

    /// USB Vendor ID → 品牌（最可靠，优先于型号字符串匹配）
    private static let vendorIDMap: [Int: CameraPlatform] = [
        0x054C: .sony,   // Sony
        0x04A9: .canon,  // Canon
        0x04B0: .nikon   // Nikon
    ]

    /// 品牌词 + 常见 USB 设备名型号特征（VID 不可用时的兜底）
    private static let rules: [Rule] = [
        Rule(platform: .nikon, keywords: [
            "nikon",
            "dsc-n",
            "coolpix",
            "z fc",
            "z 6", "z 7", "z 8", "z 9",
            "z6", "z7", "z8", "z9",
            "d3", "d4", "d5", "d6", "d7", "d8", "d850", "d750"
        ]),
        Rule(platform: .canon, keywords: [
            "canon",
            "eos ",
            "eos-",
            "powershot",
            "ixus",
            "eos m", "eos r", "eos 5d", "eos 6d", "eos 7d", "eos 90d"
        ]),
        Rule(platform: .sony, keywords: [
            "sony",
            "alpha",
            "zv-",
            "zv e",
            "ilce-",
            "ilca-",
            "dsc-",
            "nex-",
            "fx3",
            "fx30",
            "hdr-",
            "a7", "a9", "a1"
        ])
    ]

    static func detect(from info: CameraDeviceInfo) -> CameraPlatform {
        // VID 最可靠：厂商 ID 由 USB 描述符提供，优于型号字符串模糊匹配
        if let vendorID = info.usbVendorID, vendorID != 0,
           let platform = vendorIDMap[vendorID] {
            OTGLog.info(
                .detector,
                "detected platform=\(platform.rawValue), matched=usbVendorID:0x\(String(format: "%04X", vendorID)), device=\"\(info.name)\""
            )
            return platform
        }

        let text = normalizedText(from: info)

        for rule in rules {
            if let keyword = rule.keywords.first(where: { matches(text, keyword: $0) }) {
                OTGLog.info(
                    .detector,
                    "detected platform=\(rule.platform.rawValue), matched=\"\(keyword)\", text=\"\(text)\""
                )
                return rule.platform
            }
        }

        let vidHint = info.usbVendorID.map { "usbVendorID=0x\(String(format: "%04X", $0))" } ?? "usbVendorID=nil"
        OTGLog.warning(.detector, "unknown platform, \(vidHint), text=\"\(text)\"")
        return .unknown
    }

    private static func normalizedText(from info: CameraDeviceInfo) -> String {
        [info.manufacturer, info.model, info.name]
            .compactMap { $0?.lowercased() }
            .joined(separator: " ")
            .replacingOccurrences(of: "_", with: " ")
            .replacingOccurrences(of: "  ", with: " ")
            .trimmingCharacters(in: .whitespacesAndNewlines)
    }

    private static func matches(_ text: String, keyword: String) -> Bool {
        let key = keyword.lowercased()
        guard !key.isEmpty else { return false }

        if text.contains(key) {
            return true
        }

        let compactText = text.replacingOccurrences(of: " ", with: "")
            .replacingOccurrences(of: "-", with: "")
        let compactKey = key.replacingOccurrences(of: " ", with: "")
            .replacingOccurrences(of: "-", with: "")

        // 兼容 "ZV-E10" vs "ZVE10" 等空格/连字符差异
        return !compactKey.isEmpty && compactText.contains(compactKey)
    }
}
