import os

path = r"C:\JXVCTK\JxVoCongTruyenKy\_AutoVLBS\VLBS19\Scripts\LIB\VulanLib.lua"
with open(path, "r", encoding="latin1") as f:
    content = f.read()

target = "tbVulanLib.IsMenuTitle = function(nType,szSubText)\n\tif  system.MatchString(menu.GetTitle(nType),szSubText) ~= 0 then return true end\n\treturn false\nend"
target_crlf = "tbVulanLib.IsMenuTitle = function(nType,szSubText)\r\n\tif  system.MatchString(menu.GetTitle(nType),szSubText) ~= 0 then return true end\r\n\treturn false\r\nend"

new_func = """
---------------------------------------------------------------------------------------
-- Ham bat chinh xac option menu theo noi dung text (ho tro table keywords, TCVN3 & Unicode)
tbVulanLib.SelectMenuByKeywords = function(nType, tblKeywords)
\tif type(nType) ~= "number" then nType = 0 end
\tif type(tblKeywords) == "string" then tblKeywords = { tblKeywords } end
\tif menu.IsVisible(nType) == 0 then return false end

\t-- 1. Duyet qua tat ca cac dong menu hien co (0 den 15)
\tfor i = 0, 15 do
\t\tlocal szOption = menu.GetText(nType, i)
\t\tif szOption and szOption ~= "" then
\t\t\tfor _, kw in ipairs(tblKeywords) do
\t\t\t\tif kw and kw ~= "" then
\t\t\t\t\t-- So khop bang system.MatchString hoac string.find (case-insensitive)
\t\t\t\t\tif system.MatchString(szOption, kw) == 1 or string.find(string.lower(szOption), string.lower(kw), 1, true) then
\t\t\t\t\t\tsystem.Print("<color=green>[MENU TEXT] Khop tu khoa '"..kw.."' tai dong "..i..": "..szOption)
\t\t\t\t\t\tmenu.ClickIndex(nType, i)
\t\t\t\t\t\treturn true
\t\t\t\t\tend
\t\t\t\tend
\t\t\tend
\t\tend
\tend

\t-- 2. Neu chua tim thay bang GetText, thu goi truc tiep menu.ClickText cho tung tu khoa
\tfor _, kw in ipairs(tblKeywords) do
\t\tif kw and kw ~= "" then
\t\t\tif menu.ClickText(nType, kw) ~= 0 then
\t\t\t\tsystem.Print("<color=green>[MENU TEXT] Da ClickText thanh cong: "..kw)
\t\t\t\treturn true
\t\t\tend
\t\tend
\tend

\tsystem.Print("<color=red>[MENU TEXT] Khong tim thay dong nao khop voi danh sach tu khoa!")
\treturn false
end"""

if target_crlf in content:
    content = content.replace(target_crlf, target_crlf + new_func.replace("\n", "\r\n"))
    with open(path, "w", encoding="latin1") as f:
        f.write(content)
    print("SUCCESS: VulanLib.lua patched (CRLF)!")
elif target in content:
    content = content.replace(target, target + new_func)
    with open(path, "w", encoding="latin1") as f:
        f.write(content)
    print("SUCCESS: VulanLib.lua patched (LF)!")
else:
    print("ERROR: Target signature not found!")
