مَوادَس کُن گٔژھِو

Module:زٲژ ڈَبہٕ

وِکیٖپیٖڈیا پؠٹھٕ، اَکھ آزاد اِنسایکلوپیٖڈیا

"یَمہٕ ماڈیوٗلُک دَستاویز ییٚہِ Module:زٲژ ڈَبہٕ/دَستاویز جاے بَناونہٕ"

local p = {}

function p.getRank(frame)
    local args = frame.args
    if not args[1] then args = frame:getParent().args end
    
    local targetRank = args[1]
    local manualValue = args[2]

    if manualValue and manualValue ~= "" and not manualValue:find("{{{") then
        return manualValue
    end

    local entityId = args.id
    if not entityId or entityId == "" then
        entityId = mw.wikibase.getEntityIdForCurrentPage()
    end
    
    if not entityId then return "" end

    local rankMap = {
        Kingdom = "Q367", Phylum = "Q38348", Class = "Q37517", 
        Order = "Q36606", Family = "Q35409", Genus = "Q34740", 
        Species = "Q7432"
    }
    local targetQid = rankMap[targetRank]
    if not targetQid then return "" end

    local currentId = entityId
    local maxIterations = 50 

    while currentId and maxIterations > 0 do
        -- 1. Check if the current item is the rank we want
        local p105 = mw.wikibase.getBestStatements(currentId, 'P105')
        if p105 and p105[1] and p105[1].mainsnak.datavalue then
            if p105[1].mainsnak.datavalue.value.id == targetQid then
                return mw.wikibase.getLabel(currentId)
            end
        end

        -- 2. Move to Parent (P171)
        local p171 = mw.wikibase.getBestStatements(currentId, 'P171')
        if p171 and p171[1] and p171[1].mainsnak.datavalue then
            currentId = p171[1].mainsnak.datavalue.value.id
        else
            -- If we can't go higher and want Kingdom, return the current top item
            if targetRank == "Kingdom" then
                local finalLabel = mw.wikibase.getLabel(currentId)
                if finalLabel ~= "Biota" and finalLabel ~= "Life" then
                    return finalLabel
                end
            end
            currentId = nil
        end

        maxIterations = maxIterations - 1
    end

    return ""
end

return p