import Foundation
import os.log

public enum CCLog {
    private static let subsystem = "com.your.app.complycube" // ← change if you want
    private static let oslog = OSLog(subsystem: subsystem, category: "ComplyCube")

    public static func debug(_ message: String, _ meta: [String: Any]? = nil) {
        log(.debug, message, meta)
    }
    public static func info(_ message: String, _ meta: [String: Any]? = nil) {
        // .info is fine; older systems will treat it as default if needed
        log(.info, message, meta)
    }
    public static func warn(_ message: String, _ meta: [String: Any]? = nil) {
        log(.default, message, meta)
    }
    public static func error(_ message: String, _ meta: [String: Any]? = nil) {
        log(.error, message, meta)
    }
    public static func fault(_ message: String, _ meta: [String: Any]? = nil) {
        log(.fault, message, meta)
    }

    private static func log(_ type: OSLogType, _ message: String, _ meta: [String: Any]?) {
        #if DEBUG
        let composed: String
        if let meta, let json = jsonString(meta) {
            composed = "[\(label(for: type))] \(message) | \(json)"
        } else {
            composed = "[\(label(for: type))] \(message)"
        }

        if #available(iOS 10.0, *) {
            // %{public}@ avoids redaction without needing the newer privacy API
            os_log("%{public}@", log: oslog, type: type, composed)
        } else {
            print(composed)
        }
        #endif
    }

    internal static func jsonString(_ dict: [String: Any]) -> String? {
        guard JSONSerialization.isValidJSONObject(dict),
              let data = try? JSONSerialization.data(withJSONObject: dict, options: [.withoutEscapingSlashes]),
              let s = String(data: data, encoding: .utf8) else { return nil }
        return s
    }

    internal static func label(for type: OSLogType) -> String {
        switch type {
        case .debug:   return "DEBUG"
        case .info:    return "INFO"
        case .default: return "WARN"
        case .error:   return "ERROR"
        case .fault:   return "FAULT"
        default:       return "LOG"
        }
    }
}