import ContentsquareSDK
import HeapSwiftCore
import Foundation

public class PropertyValueConverter {

    /// Processes properties from React Native bridge and converts them to PropertyValue types
    /// - Parameter properties: Dictionary of properties from React Native bridge
    /// - Returns: Dictionary with values converted to PropertyValue types
    public static func processPropertyValues(_ properties: [String: Any]?) -> [String:
        ContentsquareSDK.PropertyValue]
    {
        guard let properties = properties else { return [:] }

        return properties.compactMapValues { value in
            // Handle common types that come from React Native bridge
            switch value {
            case let stringValue as String:
                return stringValue
            case let boolValue as Bool:
                return boolValue
            case let intValue as Int:
                return intValue
            case let doubleValue as Double:
                return doubleValue
            case let floatValue as Float:
                return floatValue
            case let numberValue as NSNumber:
                // NSNumber from React Native bridge - convert to appropriate type
                if CFNumberIsFloatType(numberValue) {
                    return numberValue.doubleValue
                } else {
                    return numberValue.intValue
                }
            default:
                // Try direct casting as fallback
                if let propertyValue = value as? ContentsquareSDK.PropertyValue {
                    return propertyValue
                } else {
                    log(
                        .info,
                        message:
                            "Unsupported property value type: \(type(of: value)) for value: \(value)"
                    )
                    return nil
                }
            }
        }
    }
        
    
    /// Creates a HeapSwiftCore.SourceInfo object from a dictionary
    /// - Parameter dict: Dictionary containing source info from React Native bridge
    /// - Returns: A SourceInfo object with extracted values
    public static func createSourceInfo(from dict: [String: Any]?) -> HeapSwiftCore.SourceInfo {
        let sourceName = dict?["name"] as? String ?? ""
        let sourceVersion = dict?["version"] as? String ?? ""
        let sourcePlatform = dict?["platform"] as? String ?? ""
        let sourceProperties = dict?["properties"] as? [String: Any]
        
        // Reuse processPropertyValues and cast to HeapPropertyValue
        let processed = processPropertyValues(sourceProperties)
        let processedSourceProperties = processed as! [String: any HeapPropertyValue]
        
        return HeapSwiftCore.SourceInfo(
            name: sourceName,
            version: sourceVersion,
            platform: sourcePlatform,
            properties: processedSourceProperties
        )
    }
}
