require[[strict]]
local p = {}

function p.main(frame)
    local title = mw.title.getCurrentTitle()
    local fields = mw.ext.proofreadPage.newIndex(title.text).fields

    -- Use a pattern that captures links
    -- Assuming links are formatted as [[Page Name|Display Text]] or [[Page Name]]
    local linkPattern = "%[%[([^|%]]+)[|%]]"
    local titleFields = (fields['Volume'] or '') .. (fields['Title'] or '') -- Volume often contains the more specific link
    local mainLink = titleFields:match(linkPattern)
	    
    if mainLink then
        local mainPageTitle = mw.title.new(mainLink)
        if mainPageTitle and mainPageTitle.exists then
            local mainPageContent = mainPageTitle:getContent()
            -- Find the complete AuxTOC template call including its opening and closing braces
            local auxtocComplete = mainPageContent:match('({{[aA]uxTOC|.-}})') or mainPageContent:match('({{Auxiliary [Tt]able of [Cc]ontents|.-}})')

            if auxtocComplete then
                -- Replace relative subpage links by absolute links
                local relativeLinkPattern = "%[%[/(%f[^/][^|%]]*[^|%]/])/%]%]"
                local relativeLabeledLinkPattern = "%[%[/(%f[^/][^|%]]*[^|%]/])/?(|[^%]]+)%]%]"
                local function createLink(target, label)
                	assert('/' ~= target:sub(1,1) and '/' ~= target:sub(-1), "error: 'target' link starts or ends with a '/'.")
                	return ("[[" .. mainLink .. "/" .. target .. (label or ("|" .. target)) .. "]]")
                end
                local withoutRelativeLinks = auxtocComplete:gsub(relativeLinkPattern, createLink)
                local withoutRelativeLinks = withoutRelativeLinks:gsub(relativeLabeledLinkPattern, createLink)
                -- Process the AuxTOC template with parameters as an actual template call
                local result = frame:preprocess(withoutRelativeLinks)
                return result
            else
                return "AuxTOC not found on the main page."
            end
        else
        	-- This needs to not return anything if there's a red link, since an error while the
        	-- proofread pages are processing with pywikibot, the error could lead users to remove 
        	-- the template prematurely.
            return ""
        end
    else
        return "No suitable main namespace link found in the Index page."
    end
end
return p