-- adblock_context.lua  -  right-click "Adblock Image" / "Adblock Frame" actions.
--
-- The menu (browser/defaults/settings/menus.cfg, lines 797 & 881) binds:
--   luamacro(addpattern,  Adblock Image)
--   luamacro(addpattern2, Adblock Frame)
-- The legacy implementation in lua/adblockplus.lua wrote to
-- <profile>\adblockplus\patterns.ini, but our adblock kplugin reads
-- <profile>\adblock.txt (Adblock Plus syntax) - and adblockplus.lua isn't even
-- required at startup, so addpattern was undefined and clicks were silent.
--
-- The kplugin now watches adblock.txt and re-parses on save (see adblock.cpp
-- hot reload), so appending a rule here makes it live for the very next
-- request without restarting K-Meleon.

local function abp_path()
   return (GetFolder(ProfileFolder) or "") .. "\\adblock.txt"
end

-- Read adblock.txt as an array of trimmed lines (preserves comments).
local function abp_read()
   local out = {}
   local f = io.open(abp_path(), "r")
   if not f then return out end
   for line in f:lines() do
      if line:sub(-1) == "\r" then line = line:sub(1, -2) end
      table.insert(out, line)
   end
   f:close()
   return out
end

local function abp_append(rule)
   local f, err = io.open(abp_path(), "a")
   if not f then return false, err end
   f:write(rule, "\n")
   f:close()
   return true
end

-- Build a default ABP rule from a URL. ||host/path/file blocks that exact
-- resource. Drop query string + fragment (almost never useful in the pattern).
local function abp_default_rule(url)
   if type(url) ~= "string" or url == "" then return "" end
   local s = url:gsub("^%w+:/+", "")
   s = s:gsub("#.*$", ""):gsub("%?.*$", "")
   return "||" .. s
end

-- Get URL from the right-click context, prompt the user (with sensible
-- default), append to adblock.txt. The kplugin's file watcher takes care of
-- making it live.
--
-- `which` is the Window_* enum value (NOT a string) - ImageURL / FrameURL etc.
-- are PER-WINDOW vars retrieved via km.GetWindowVar(type), NOT globals. The
-- original code tried GetGlobalVar(TYPE_STRING, "ImageURL") which always
-- returned "" (no such pref), so the menu silently no-op'd.
-- Small diag helper - writes to luamacro_errors.log so we can see what the
-- menu click actually did (empty URL? cancel? duplicate? write failed?).
local function abp_log(msg)
   local f = io.open((BROWSERPATH or "") .. "luamacro_errors.log", "a")
   if f then f:write("[adblock_context] " .. tostring(msg) .. "\n"); f:close() end
end

local function abp_block_url(which)
   local url = km.GetWindowVar(which)
   abp_log("addpattern: url=" .. tostring(url))
   if not url or url == "" then
      alert("No image/frame URL found at the click position.", "Adblock", ICON_INFO)
      return
   end
   local rule = prompt(_ADBLOCK_RULE_PROMPT or "Edit rule, OK to block:",
                       _ADBLOCK_RULE_TITLE  or "Add adblock rule",
                       abp_default_rule(url))
   if not rule then abp_log("addpattern: cancelled"); return end
   rule = rule:gsub("^%s+", ""):gsub("%s+$", "")
   if rule == "" then abp_log("addpattern: empty rule"); return end
   for _, r in ipairs(abp_read()) do
      if r == rule then
         alert(_ADBLOCK_DUPE or "Rule already in adblock.txt.",
               "Adblock", ICON_INFO)
         return
      end
   end
   local ok, err = abp_append(rule)
   if not ok then
      abp_log("addpattern: WRITE FAILED " .. tostring(err))
      alert("Failed to write adblock.txt: " .. tostring(err), "Adblock", ICON_STOP)
      return
   end
   abp_log("addpattern: added " .. rule)
   SetStatusBarText((_ADBLOCK_ADDED or "Rule added:") .. "  " .. rule)
end

-- Bind to the menu names already in menus.cfg.
function addpattern(hwnd)  abp_block_url(Window_ImageURL) end
function addpattern2(hwnd) abp_block_url(Window_FrameURL) end
