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

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;'>[FD2 Error: %s. Page: %s]</span>", context or "Unknown Context", safe_details)
end

--- Видаляє вікі-посилання [[link|text]] і [[link]]
local function clean_wikilinks(text)
    if not text then return nil end
    text = mw.ustring.gsub(text, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2")
    text = mw.ustring.gsub(text, "%[%[([^%]]+)%]%]", "%1")
    return mw.text.trim(text)
end

----------------------------------------------------------------------
-- ГОЛОВНИЙ ПОШУК (Надійно парсить без goto, шукає "Кексік")
----------------------------------------------------------------------

local function fetch_from_table(page_title, passed_player_name, column_index)
    -- !!! ЖОРСТКЕ КОДУВАННЯ
    local player_name = "Кексік" 
    
    if not player_name or player_name == "" then
        return error_output("No Player Name (Hardcoded)", page_title) 
    end
    
    local title = mw.title.new(page_title)
    if not title or not title.exists then 
        return error_output("Page Missing", page_title)
    end

    local content = title:getContent()
    if not content then return error_output("Content Read Fail", page_title) end

    local table_content = mw.ustring.match(content, "{|.-([|].-.-[|]})")
    if not table_content then 
        return error_output("Table Missing", page_title)
    end

    local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
    local player_pattern = "%[%[" .. escaped .. "%]%]" 

    local result = nil
    
    -- Ітерація по всіх рядках, що починаються з `|-`
    for row in mw.ustring.gmatch(table_content, "\n%s*|-[^%s]*\n(.-)") do
        
        -- Перевіряємо, чи містить рядок ім'я гравця у форматі [[Кексік]]
        if mw.ustring.find(row, player_pattern, 1, true) then
            
            local cell_data = {}
            local cell_part_string = ""
            local first_cell_match = mw.ustring.match(row, "^%s*[|]%s*(.-)%s*[|][|](.*)$") -- Захоплює першу комірку та решту

            if first_cell_match then
                -- first_cell_match = "001"
                -- second_match (неявний) = " [[Кексік]] || 29.12.2022 || [[Демон]]"
                
                -- Розбиваємо за допомогою string.match для більшої надійності:
                local first_content, rest_of_row = mw.ustring.match(row, "^%s*[|]%s*(.-)%s*[|][|](.*)$")

                if first_content then
                    table.insert(cell_data, mw.text.trim(first_content))
                    cell_part_string = rest_of_row
                end
            end

            -- Витягуємо решту комірок, розділених '||'
            if cell_part_string then
                local parts = mw.text.split(cell_part_string, '||')
                for _, part in ipairs(parts) do
                    table.insert(cell_data, mw.text.trim(part))
                end
            end
            
            -- Перевірка, що ми знайшли [[Кексік]] саме в Колонці 2
            if #cell_data >= 2 and mw.ustring.find(cell_data[2], player_pattern) then
                
                -- Перевірка, чи існує потрібна колонка
                if column_index <= #cell_data and cell_data[column_index] then
                    result = clean_wikilinks(cell_data[column_index])
                    break -- Знайшли, виходимо з циклу gmatch
                end
            end
        end
    end

    return result
end

----------------------------------------------------------------------
-- ФУНКЦІЇ ДЛЯ {{MCC Player New}} (без змін)
----------------------------------------------------------------------

function p.recruiter(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 4) 
    
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
    
    if raw == "Відсутній" or raw == "-" then return "Не вказано" end
    return raw or "Не вказано"
end

function p.date_added(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 3) 
    
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
    
    return raw or "Невідомо"
end

function p.prize_pool(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Призовий_фонд", name, 3) 
    
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
    
    if raw then 
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
    end
    return (raw or "0") .. " ₴"
end

function p.foundation(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Фундація", name, 3)
    
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
    
    if raw then 
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
    end
    return (raw or "0") .. " ₴"
end

function p.final(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Фіналіст", name, 3)
    
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
    
    local count = raw and mw.ustring.match(raw, "(%d+)")
    
    if count then
        return count
    else
        return "0"
    end
end

function p.season_result(frame)
    return nil 
end

return p