local m = {}

-- 比较输出函数
local function compareOutputs(output1, output2)
    local diff = {}
    local len1, len2 = #output1, #output2
    local maxLen = math.max(len1, len2)

    for i = 1, maxLen do
        local char1 = output1:sub(i, i)
        local char2 = output2:sub(i, i)
        if char1 ~= char2 then
            table.insert(diff, {index = i, char1 = char1, char2 = char2})
        end
    end

    return diff
end

function m.runTests(frame)
    -- 测试页面和段落
    local page = "Page:ROC1912-01-29臨時政府公報01.pdf/1"
    local section = "臨時大總統誓詞"
    
    -- 定义解析器函数的名称和参数
    local lstFunctionName = "#lst"
    local lstArgs = {page, section}
    local invokeArgs = {"lst", "joinedLines", "\n", page, section}

    -- 使用 pcall 来安全地调用 #lst
    local successLst, lstOutput = pcall(function()
        return frame:callParserFunction{name = lstFunctionName, args = lstArgs}
    end)

    -- 使用 pcall 来安全地调用 #invoke:lst|joinedLines
    local successInvoke, joinedLinesOutput = pcall(function()
        return frame:callParserFunction{name = "#invoke", args = invokeArgs}
    end)

    -- 检查调用是否成功
    if not successLst then
        return "Error calling #lst: " .. tostring(lstOutput)
    end

    if not successInvoke then
        return "Error calling #invoke:lst|joinedLines: " .. tostring(joinedLinesOutput)
    end

    -- 检查输出是否为 nil
    if lstOutput == nil or joinedLinesOutput == nil then
        return "One of the outputs is nil."
    end

    -- 对比输出
    local differences = compareOutputs(lstOutput, joinedLinesOutput)

    if #differences > 0 then
        local diffReport = "Differences found:\n"
        for _, d in ipairs(differences) do
            local char1 = d.char1 or 'nil'
            local char2 = d.char2 or 'nil'
            diffReport = diffReport .. string.format("Index: %d, #lst: '%s' (code: %d), #invoke: '%s' (code: %d)\n",
                d.index, char1, char1:byte(), char2, char2:byte())
        end

        -- 添加输出调试信息
        diffReport = diffReport .. "\nFull outputs:\n\n#lst output:\n" .. lstOutput .. "\n\n#invoke output:\n" .. joinedLinesOutput

        return "Test Failed: Outputs are different.\n" .. diffReport
    else
        return "Test Passed: Outputs are the same."
    end
end

return m