//
//  OTGLog.swift
//  otg_swift
//

import Foundation
import os

/// OTG 统一日志，Xcode Console 过滤关键字：`[OTG]`
enum OTGLog {

    /// Console 过滤前缀
    static let filterPrefix = "[OTG]"

    /// 日志级别，映射 os.Logger 与控制台输出
    enum Level: String {
        /// 调试细节，仅 DEBUG 构建打印到 Xcode Console
        case debug = "DEBUG"
        /// 正常流程节点（连接、PTP 成功等）
        case info = "INFO"
        /// 可恢复异常或降级路径
        case warning = "WARN"
        /// 失败路径，需用户或开发者关注
        case error = "ERROR"
    }

    /// 日志分类，对应 Console 中 `[Category]` 段
    enum Category: String {
        /// ConnectionManager、ICCamera 扫描与 Session
        case connection = "Connection"
        /// 通用 PTP 命令发送与解析
        case ptp = "PTP"
        /// PlatformDetector 品牌识别
        case detector = "Detector"
        /// CameraFactory Driver 创建
        case factory = "Factory"
        /// NikonCameraDriver
        case nikon = "Nikon"
        /// CanonCameraDriver
        case canon = "Canon"
        /// Sony Driver、SDIO 与边拍边传
        case sony = "Sony"
    }

    private static let osLog = Logger(
        subsystem: Bundle.main.bundleIdentifier ?? "otg_swift",
        category: "OTG"
    )

    static func debug(
        _ category: Category,
        _ message: @autoclosure () -> String,
        file: String = #file,
        line: Int = #line
    ) {
        log(.debug, category: category, message: message(), file: file, line: line)
    }

    static func info(
        _ category: Category,
        _ message: @autoclosure () -> String,
        file: String = #file,
        line: Int = #line
    ) {
        log(.info, category: category, message: message(), file: file, line: line)
    }

    static func warning(
        _ category: Category,
        _ message: @autoclosure () -> String,
        file: String = #file,
        line: Int = #line
    ) {
        log(.warning, category: category, message: message(), file: file, line: line)
    }

    static func error(
        _ category: Category,
        _ message: @autoclosure () -> String,
        file: String = #file,
        line: Int = #line
    ) {
        log(.error, category: category, message: message(), file: file, line: line)
    }

    private static func log(
        _ level: Level,
        category: Category,
        message: String,
        file: String,
        line: Int
    ) {
        let fileName = (file as NSString).lastPathComponent
        let formatted = "\(filterPrefix)[\(level.rawValue)][\(category.rawValue)] \(message) (\(fileName):\(line))"

        #if DEBUG
        // DEBUG 仅用 print，避免与 osLog 在 Xcode Console 重复输出
        print(formatted)
        #else
        switch level {
        case .debug:
            osLog.debug("\(formatted)")
        case .info:
            osLog.info("\(formatted)")
        case .warning:
            osLog.warning("\(formatted)")
        case .error:
            osLog.error("\(formatted)")
        }
        #endif
    }
}
