require('strict')

local p = {}

-- can we use Extension:CategoryToolbox?
local function pageInCategory(content, category)
	return content:match('%[%[Category:' .. category .. '%]%]') ~= nil
end

function p.check()
    local mwTitle = mw.title.getCurrentTitle()
    local content = mwTitle:getContent()
    local hasSoundFilmCategories = pageInCategory(content, 'Sound film') or pageInCategory(content, 'Sound cartoons') or pageInCategory(content, 'Part%-talkies')
    -- local hasSoundFilmOrCartoonsCategory = pageInCategory(content, 'Sound film')
	
    if not hasSoundFilmCategories then
        return ""
    end
    
    local entityId = mw.wikibase.getEntityIdForCurrentPage()
    if not entityId then
        return ""
    end
    
    local propertyId = 'P577' -- Property ID for 'publication date'
    local releaseDate = mw.wikibase.getBestStatements(entityId, propertyId)[1]
    
    if releaseDate and releaseDate.mainsnak and releaseDate.mainsnak.datavalue and releaseDate.mainsnak.datavalue.value then
        local dateValue = releaseDate.mainsnak.datavalue.value.time
        -- Match the year and month in the date string
        local year, month = dateValue:match('%+(%d%d%d%d)%-(%d%d)%-')
        
        if year then
            local yearNum = tonumber(year)
            if yearNum and yearNum >= 1927 and yearNum <= 1933 then
                return "[[Category:Pre-Code films]]"
            elseif yearNum == 1934 then
                if month then
                    local monthNum = tonumber(month)
                    if monthNum and monthNum < 7 then
                        return "[[Category:Pre-Code films]]"
                    end
                end
            end
        end
    end
    
    return ""
end

return p