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

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

--- Видаляє вікі-посилання [[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

--- Створює посилання на турнір
local function get_tournament_link(short_name, full_name)
    if short_name == "WCCI" then
        return "[[Women's Closed Cup I|WCCI]]"
    end
    -- Додати інші скорочення тут
    return short_name
end

--- Визначає роль гравця в грі
local function get_player_role(player_name, cells)
    -- Колонки: 1-Формат, 2-Тип, 3-Турнір, 4-Скорочення
    -- 5-10: Мирні (6 гравців)
    -- 11: Шериф
    -- 12-13: Мафія (2 гравці)
    -- 14: Дон
    -- 15: Результат
    -- 16: Посилання
    
    -- Перевіряємо Мирних (колонки 5-10)
    for i = 5, 10 do
        if cells[i] and clean_wikilinks(cells[i]) == player_name then
            return "Мирний"
        end
    end
    
    -- Перевіряємо Шерифа (колонка 11)
    if cells[11] and clean_wikilinks(cells[11]) == player_name then
        return "Шериф"
    end
    
    -- Перевіряємо Мафію (колонки 12-13)
    for i = 12, 13 do
        if cells[i] and clean_wikilinks(cells[i]) == player_name then
            return "Мафія"
        end
    end
    
    -- Перевіряємо Дона (колонка 14)
    if cells[14] and clean_wikilinks(cells[14]) == player_name then
        return "Дон"
    end
    
    return "Невідомо"
end

--- Визначає результат для гравця
local function get_player_result(role, game_result)
    if not game_result or game_result == "" then
        return "Невідомо"
    end
    
    game_result = mw.text.trim(game_result)
    
    -- Місто перемогло
    if game_result == "Місто" or game_result == "Мирні" then
        if role == "Мирний" or role == "Шериф" then
            return "Перемога"
        else
            return "Поразка"
        end
    end
    
    -- Мафія перемогла
    if game_result == "Мафія" then
        if role == "Мафія" or role == "Дон" then
            return "Перемога"
        else
            return "Поразка"
        end
    end
    
    return "Невідомо"
end

--- Отримує список ігор гравця
local function get_player_games_list(player_name)
    local title = mw.title.new("Ігри")
    if not title or not title.exists then 
        return nil
    end
    
    local content = title:getContent()
    if not content then 
        return nil
    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
    end
    
    local table_content = mw.ustring.sub(content, table_start, table_end + 1)
    
    -- Збираємо всі рядки
    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
    
    local games = {}
    
    -- Обробляємо кожен рядок
    for _, row in ipairs(rows) do
        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
        
        -- Перевіряємо чи гравець є в цій грі
        local player_in_game = false
        for i = 5, 14 do
            if cells[i] and clean_wikilinks(cells[i]) == player_name then
                player_in_game = true
                break
            end
        end
        
        if player_in_game and #cells >= 15 then
            local tournament = cells[3] or ""
            local short_name = cells[4] or ""
            local game_result = cells[15] or ""
            local link = cells[16] or ""
            
            local role = get_player_role(player_name, cells)
            local result = get_player_result(role, game_result)
            
            table.insert(games, {
                tournament = tournament,
                short = short_name,
                role = role,
                result = result,
                link = link
            })
        end
    end
    
    return games
end

--- Головна функція для виведення ігор гравця
function p.player_games(frame)
    local player_name = frame.args.player
    
    if not player_name or player_name == "" then
        return error_output("No Player Name", "")
    end
    
    local games = get_player_games_list(player_name)
    
    if not games then
        return error_output("Cannot Load Games", "Ігри")
    end
    
    if #games == 0 then
        return "''Ігор не знайдено''"
    end
    
    -- Генеруємо таблицю з заголовками
    local table_html = {
        '{| class="wikitable sortable" style="width: 100%; font-size: 14.5px;"',
        '! Турнір !! Роль !! Результат !! Запис',
        '|-'
    }
    
    for _, game in ipairs(games) do
        local result_text = game.result
        if game.result == "Перемога" then
            result_text = "<span style='color:#4caf50; font-weight:normal;'>Перемога</span>"
        elseif game.result == "Поразка" then
            result_text = "<span style='color:indianred; font-weight:normal;'>Поразка</span>"
        end
        
        local link_display = ""
        if game.link and game.link ~= "" then
            link_display = string.format(
                '<a href="%s" target="_blank" style="display:inline-block; padding:4px 8px; background-color:white; color:black; border-radius:4px; font-size:13px; text-decoration:none; transition:opacity 0.2s;" onmouseover="this.style.opacity=\'0.7\'" onmouseout="this.style.opacity=\'1\'">Запис</a>',
                game.link
            )
        end
        
        local tournament_link = get_tournament_link(game.short, game.tournament)
        
        table.insert(table_html, string.format(
            '| style="text-align:center; padding: 8px;" | %s || style="text-align:center; padding: 8px;" | %s || style="text-align:center; padding: 8px;" | %s || style="text-align:center; padding: 8px;" | %s',
            tournament_link,
            game.role,
            result_text,
            link_display
        ))
        table.insert(table_html, '|-')
    end
    
    table.insert(table_html, '|}')
    
    return table.concat(table_html, '\n')
end

--- Функція для отримання кількості ігор гравця
function p.games_count(frame)
    local player_name = frame.args.player
    
    if not player_name or player_name == "" then
        return "0"
    end
    
    local games = get_player_games_list(player_name)
    
    if not games then
        return "0"
    end
    
    return tostring(#games)
end

return p