import SafariServices
import os.log

class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {

    func beginRequest(with context: NSExtensionContext) {
        let request = context.inputItems.first as? NSExtensionItem

        let profile: UUID?
        if #available(iOS 17.0, macOS 14.0, *) {
            profile = request?.userInfo?[SFExtensionProfileKey] as? UUID
        } else {
            profile = request?.userInfo?["profile"] as? UUID
        }

        let message: Any?
        if #available(iOS 15.0, macOS 11.0, *) {
            message = request?.userInfo?[SFExtensionMessageKey]
        } else {
            message = request?.userInfo?["message"]
        }

        os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@ (profile: %@)", String(describing: message), profile?.uuidString ?? "none")

        if let messageDict = message as? [String: Any],
           messageDict["action"] as? String == "openShortcutSettings" {
            openShortcutSettings(context: context)
            return
        }

        let response = NSExtensionItem()
        if #available(iOS 15.0, macOS 11.0, *) {
            response.userInfo = [ SFExtensionMessageKey: [ "echo": message ] ]
        } else {
            response.userInfo = [ "message": [ "echo": message ] ]
        }

        context.completeRequest(returningItems: [ response ], completionHandler: nil)
    }

    /// Open Safari Settings → Extensions for this extension, which lists its keyboard shortcuts.
    private func openShortcutSettings(context: NSExtensionContext) {
        var success = false
        #if os(macOS)
        let identifier = Bundle.main.bundleIdentifier ?? "net.aliasvault.safari.extension"
        SFSafariApplication.showPreferencesForExtension(withIdentifier: identifier) { error in
            if let error = error {
                os_log(.error, "Failed to open Safari extension preferences: %@", error.localizedDescription)
            }
        }
        success = true
        #endif

        let response = NSExtensionItem()
        if #available(iOS 15.0, macOS 11.0, *) {
            response.userInfo = [ SFExtensionMessageKey: [ "success": success ] ]
        } else {
            response.userInfo = [ "message": [ "success": success ] ]
        }
        context.completeRequest(returningItems: [ response ], completionHandler: nil)
    }

}
