Документацію для цього модуля можна створити у Модуль:FetchData3/документація

local p = {}

--- Функція для виведення помилки
local function error_output(context, error_details)
    local safe_details = error_details or "N/A" 
    return string.format("<span style='color:red; font-weight:bold;'>[FD3 Error: %s. Details: %s]</span>", 
        context or "Unknown Context", safe_details)
end

--- Отримує заголовки та рядок гравця з таблиці
local function get_player_row(page_title, player_name)
    local title = mw.title.new(page_title)
    if not title or not title.exists then 
        return nil, error_output("Page Missing", page_title)
    end
    
    local content = title:getContent()
    if not content then 
        return nil, error_output("Content Read Fail", page_title) 
    end
    
    -- Знаходимо таблицю
    local table_start = mw.ustring.find(content, "{|")
    local table_end = mw.ustring.find(content, "|}", table_start)
    
    if not table_start or not table_end then
        return nil, error_output("Table Missing", page_title)
    end
    
    local table_content = mw.ustring.sub(content, table_start, table_end + 1)
    
    -- Отримуємо заголовки (перший рядок після {|)
    local headers = {}
    local first_row = mw.ustring.match(table_content, "{|[^\n]*\n!(.-)[\n]")
    
    if first_row then
        -- Розбиваємо заголовки по ||
        for header in mw.ustring.gmatch(first_row, "([^|]+)") do
            local trimmed = mw.text.trim(header)
            if trimmed ~= "" then
                table.insert(headers, trimmed)
            end
        end
    end
    
    if #headers == 0 then
        return nil, error_output("No Headers Found", page_title)
    end
    
    -- Шукаємо рядок з гравцем
    local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
    local player_pattern = "%[%[" .. escaped .. "%]%]"
    
    -- Збираємо всі рядки
    local rows = {}
    for row in mw.ustring.gmatch(table_content, "|-\n(.-)\n|-") do
        table.insert(rows, row)
    end
    
    local last_row = mw.ustring.match(table_content, "|-\n(.-)%s*|}")
    if last_row then
        table.insert(rows, last_row)
    end
    
    -- Обробляємо кожен рядок
    for _, row in ipairs(rows) do
        if mw.ustring.find(row, player_pattern) then
            local cells = {}
            row = mw.ustring.gsub(row, "^%s*|%s*", "")
            
            for cell in mw.ustring.gmatch(row, "([^|]+)") do
                local trimmed = mw.text.trim(cell)
                if trimmed ~= "" then
                    table.insert(cells, trimmed)
                end
            end
            
            return {headers = headers, cells = cells}
        end
    end
    
    return nil, error_output("Player Not Found", player_name)
end

--- Генерує іконку медалі
local function get_medal_icon(value)
    if value == "1" then
        return "[[Файл:Gold.png|1-е Місце]]"
    elseif value == "2" then
        return "[[Файл:Silver.png|2-е Місце]]"
    elseif value == "3" then
        return "[[Файл:Bronze.png|3-е Місце]]"
    elseif value == "4" then
        return "[[Файл:Finalist.png|Фіналіст]]"
    elseif value == "S" or mw.ustring.match(value, "^S%d") then
        return "[[Файл:Star.png|Найкращий]]"
    else
        return ""
    end
end

--- Генерує посилання на турнір
local function get_tournament_link(header_name)
    -- Видаляємо (Ф) та (Р) для відображення, але залишаємо для посилання
    local display_name = header_name
    local link_name = mw.ustring.gsub(header_name, "%s*%(Ф%)%s*", "")
    link_name = mw.ustring.gsub(link_name, "%s*%(Р%)%s*", "")
    link_name = mw.text.trim(link_name)
    
    -- Якщо назви однакові, просто посилання
    if link_name == display_name then
        return string.format("[[%s]]", link_name)
    else
        return string.format("[[%s|%s]]", link_name, display_name)
    end
end

----------------------------------------------------------------------
-- ГОЛОВНА ФУНКЦІЯ ДЛЯ ОТРИМАННЯ ТИТУЛІВ
----------------------------------------------------------------------
function p.titles(frame)
    local name = frame.args.player
    
    if not name or name == "" then
        return error_output("No Player Name", "")
    end
    
    local data, err = get_player_row("Титули", name)
    
    if not data then
        return err or "Немає титулів"
    end
    
    local titles = {}
    
    -- Пропускаємо першу колонку (ім'я гравця)
    for i = 2, #data.cells do
        local cell_value = data.cells[i]
        
        if cell_value and cell_value ~= "" then
            local medal = get_medal_icon(cell_value)
            local tournament = get_tournament_link(data.headers[i])
            
            if medal ~= "" then
                table.insert(titles, string.format("* %s '''%s'''", medal, tournament))
            end
        end
    end
    
    if #titles == 0 then
        return "''Відсутні''"
    end
    
    return table.concat(titles, "\n")
end

return p