import Foundation

struct NotificationConfig {
  let senderIdKey: String
  let avatarUrlKey: String?
  let conversationIdKey: String?
  let groupNameKey: String?
  let groupAvatarUrlKey: String?
}

enum ConfigReader {

  /// Returns the App Group container URL, reading the group ID from the extension's Info.plist.
  static func appGroupContainerUrl() -> URL? {
    guard let appGroupId = Bundle.main.object(forInfoDictionaryKey: "AppGroupId") as? String else {
      return nil
    }
    return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupId)
  }

  /// Read the runtime JSON config written by the JS side.
  static func readConfig() -> NotificationConfig? {
    guard let containerUrl = appGroupContainerUrl() else { return nil }

    let configUrl = containerUrl.appendingPathComponent("Library/config.json")
    guard let data = try? Data(contentsOf: configUrl),
          let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
          let senderIdKey = json["senderIdKey"] as? String else {
      return nil
    }

    return NotificationConfig(
      senderIdKey: senderIdKey,
      avatarUrlKey: json["avatarUrlKey"] as? String,
      conversationIdKey: json["conversationIdKey"] as? String,
      groupNameKey: json["groupNameKey"] as? String,
      groupAvatarUrlKey: json["groupAvatarUrlKey"] as? String
    )
  }

  /// Extract a string value from a nested dictionary using dot-separated key path.
  static func extractValue(from dict: [AnyHashable: Any], keyPath: String) -> String? {
    let keys = keyPath.split(separator: ".").map(String.init)
    var current: Any = dict
    for key in keys {
      if let currentDict = current as? [String: Any], let next = currentDict[key] {
        current = next
      } else if let currentDict = current as? [AnyHashable: Any], let next = currentDict[key] {
        current = next
      } else {
        return nil
      }
    }
    if let str = current as? String {
      return str
    }
    if let num = current as? NSNumber {
      return num.stringValue
    }
    return nil
  }

  /// Check if logging is enabled (read from extension's Info.plist).
  static func isLoggingEnabled() -> Bool {
    return Bundle.main.object(forInfoDictionaryKey: "EnableLogging") as? Bool ?? false
  }
}
