-- ~/.hammerspoon/affine_quick_note.lua
local obj = {}

-- CONFIGURATION
local NODE_PATH = "/opt/homebrew/bin/node" 
local SYNC_SCRIPT = os.getenv("HOME") .. "/.hammerspoon/scripts/sync_note.js" 

local function affineQuickNote(text)
    local syncNotify = hs.notify.new({
        title="AFFiNE Sync", 
        informativeText="Syncing large note... Please wait."
    }):send()
    
    local task = hs.task.new(NODE_PATH, function(exitCode, stdOut, stdErr)
        syncNotify:withdraw()
        if exitCode == 0 then
            hs.notify.new({title="AFFiNE Success", informativeText="Multi-line note appended."}):send()
        else
            hs.notify.new({title="AFFiNE Error", informativeText="Check Console."}):send()
            print("Sync Error: " .. stdErr)
        end
    end, {SYNC_SCRIPT, text})

    task:start()
end

-- Function to trigger a proper macOS multi-line text box
local function getMultiLineInput()
    local appleScript = [[
        tell application "System Events"
            activate
            set theResponse to display dialog "Enter your detailed note:" default answer "" with title "AFFiNE Multi-Line Capture" buttons {"Cancel", "Send"} default button "Send"
            return text returned of theResponse
        end tell
    ]]
    
    local ok, result = hs.applescript(appleScript)
    if ok and result ~= "" then
        return result
    end
    return nil
end

function obj.init()
    if hyper then
        hs.hotkey.bind(hyper, "N", function()
            local text = getMultiLineInput()
            if text then
                affineQuickNote(text)
            end
        end)
    else
        print("AFFiNE Error: 'hyper' variable not found.")
    end
end

return obj