Module:BassaridiaForecast: Difference between revisions

From MicrasWiki
Jump to navigationJump to search
(Undo revision 350265 by NewZimiaGov (talk))
Tag: Undo
No edit summary
Line 1: Line 1:
---------------------------------------------------------
---------------------------------------------------------
-- Module:WeatherForecastTable
-- Module:WeatherForecastTable
-- Generates a daily forecast table with:
-- Generates a fully updated daily forecast table with:
--  • Random daily weather factors for each city
--  • Random weather factors for each city, seeded by os.time()
--  • PSSC date logic (Atosiel, Thalassiel, Opsitheiel)
--  • PSSC date logic (Atosiel, Thalassiel, Opsitheiel)
--  • All 8 spelled-out climates, each 3 seasons × 10 events
--  • All 8 spelled-out climates × 3 seasons × 10 events each
--  • All major & minor cities in Bassaridia Vaeringheim,
--  • All major & minor cities in Bassaridia Vaeringheim,
--    New South Jangsong, and Haifan Bassaridia
--    New South Jangsong, and Haifan Bassaridia
--  • High/Low in Celsius behind the scenes, displayed in °F
--  • High/Low in Celsius behind the scenes, displayed in °F only
--  • Humidity, chance of rain, wind direction, wind speed
--  • Humidity, chance of rain, wind direction, wind speed
--  • Color-coded "Today's Weather" cell by event keywords
--  • Color-coded "Today's Weather" cell by event keywords
--  • **Natural Disaster Advisory** that merges the city’s
--  • Natural Disaster Advisory merges each city's typical hazards
--    typical hazards with today's forecast conditions
--    with any triggered by today's weather text (storm, dust, etc.)
--  • No numeric checks or extra error handling
--  • No numeric checks or extra error handling
---------------------------------------------------------
---------------------------------------------------------
Line 19: Line 19:
---------------------------------------------------------
---------------------------------------------------------
-- 0. Random Seed
-- 0. Random Seed
-- Ensures new random results each day.
-- Ensures new random results every day or invocation.
---------------------------------------------------------
---------------------------------------------------------
math.randomseed(os.time())
math.randomseed(os.time())
Line 26: Line 26:
-- 1. PSSC Calendar System
-- 1. PSSC Calendar System
---------------------------------------------------------
---------------------------------------------------------
local function getCurrentDateInfo()
local function getCurrentDateInfo()
     local startDate = os.time({year = 1999, month = 8, day = 6})
     local startDate = os.time({year = 1999, month = 8, day = 6})
Line 46: Line 45:


---------------------------------------------------------
---------------------------------------------------------
-- 2. Determine Season (1..61=Atosiel, 62..122=Thalassiel, 123..183=Opsitheiel)
-- 2. Determine Season
-- (Atosiel = days 1..61; Thalassiel = 62..122; Opsitheiel = 123..183)
---------------------------------------------------------
---------------------------------------------------------
local function getSeasonName(dayOfYear)
local function getSeasonName(dayOfYear)
     if dayOfYear <= 61 then
     if dayOfYear <= 61 then
Line 60: Line 59:


---------------------------------------------------------
---------------------------------------------------------
-- 3. Weather Events Table
-- 3. Weather Events Table (8 climates × 3 seasons × 10 events)
-- Each climate + season has 10 possible weather events.
---------------------------------------------------------
---------------------------------------------------------
local climateEvents = {
local climateEvents = {
     ["Humid Subtropical"] = {
     ["Humid Subtropical"] = {
Line 372: Line 369:


---------------------------------------------------------
---------------------------------------------------------
-- 4. Temperature Ranges by Climate
-- 5. Typical Disasters for Each City
-- (Stored internally in Celsius, displayed as Fahrenheit)
---------------------------------------------------------
---------------------------------------------------------
local cityDisasters = {
    ["Vaeringheim"]      = "Seasonal storms and lake-driven floods",
    ["Luminaria"]        = "River floods during heavy rains",
    ["Serena"]            = "Snowstorms at higher elevations",
    ["Pyralis"]          = "Occasional steam vent eruptions",
    ["Symphonara"]        = "Landslides on steep slopes",
    ["Aurelia"]          = "Droughts and brushfires",
    ["Somniumpolis"]      = "Recurrent flooding in marshes",
    ["Nexa"]              = "Localized mudslides",
    ["Lunalis Sancta"]    = "Fog-related travel hazards",
    ["Sylvapolis"]        = "Swamp flooding",
    ["Saluria"]          = "River floods",
    ["Aetherium"]        = "Blizzards",
    ["Ferrum Citadel"]    = "Dust storms and heatwaves",
    ["Acheron"]          = "Occasional flash floods",
    ["Erythros"]          = "Tar-pit gas releases",
    ["Catonis Atrium"]    = "Landslides on steep slopes",
    ["Delphica"]          = "Coastal storms",
    ["Koinonía"]          = "Mild landslides",
    ["Aureum"]            = "Summer wildfires",


local climateTemperature = {
     ["Skýrophos"]        = "Cliff erosion and sea storms",
     ["Humid Subtropical"] = {
    ["Bjornopolis"]      = "Flood surges near waterfalls",
         Atosiel    = { hiMin=18, hiMax=26, loMin=10, loMax=16, humMin=60, humMax=80 },
    ["Aegirheim"]         = "Coastal gales, blizzards",
        Thalassiel  = { hiMin=25, hiMax=34, loMin=19, loMax=24, humMin=65, humMax=90 },
     ["Norsolyra"]        = "Marsh flooding",
         Opsitheiel  = { hiMin=20, hiMax=28, loMin=12, loMax=18, humMin=50, humMax=75 }
    ["Thorsalon"]         = "Occasional cliff collapses",
    },
 
     ["Oceanic"] = {
     ["Pelagia"]          = "Sandstorms",
         Atosiel    = { hiMin=10, hiMax=17, loMin=5,  loMax=12, humMin=70, humMax=90 },
     ["Myrene"]           = "Minor landslides",
         Thalassiel  = { hiMin=14, hiMax=21, loMin=9,  loMax=14, humMin=65, humMax=85 },
     ["Thyrea"]            = "Lake overflows, marsh flooding",
        Opsitheiel  = { hiMin=5,  hiMax=12, loMin=1,  loMax=6,  humMin=70, humMax=90 }
     ["Ephyra"]           = "Avalanches in higher passes",
     },
     ["Halicarn"]         = "Occasional flash floods",
     ["Subpolar Oceanic"] = {
 
        Atosiel     = { hiMin=3, hiMax=9,  loMin=-2, loMax=3,  humMin=70, humMax=95 },
     ["Keybir-Aviv"]       = "Shoreline flooding",
        Thalassiel  = { hiMin=6,  hiMax=12, loMin=1,  loMax=6,  humMin=70, humMax=90 },
     ["Tel-Amin"]          = "Wildfires in dry spells",
        Opsitheiel  = { hiMin=-1, hiMax=4,  loMin=-6, loMax=-1, humMin=75, humMax=95 }
     ["Diamandis"]        = "Droughts",
    },
    ["Jogi"]              = "River floods",
     ["Mediterranean (Hot Summer)"] = {
    ["Lewisburg"]         = "Swamp overflows",
        Atosiel    = { hiMin=15, hiMax=21, loMin=7,  loMax=12, humMin=40, humMax=60 },
 
        Thalassiel  = { hiMin=25, hiMax=35, loMin=15, loMax=20, humMin=30, humMax=50 },
     ["Thermosalem"]       = "Occasional landslides near hot springs",
        Opsitheiel  = { hiMin=12, hiMax=18, loMin=5,  loMax=10, humMin=45, humMax=65 }
     ["Akróstadium"]      = "Dust devils on dry slopes",
    },
    ["Sufriya"]          = "Storm surges from inlet",
     ["Hot Desert"] = {
    ["Lykopolis"]         = "Mine collapses, gas leaks"
        Atosiel    = { hiMin=25, hiMax=35, loMin=12, loMax=18, humMin=10, humMax=30 },
        Thalassiel  = { hiMin=35, hiMax=45, loMin=25, loMax=30, humMin=5,  humMax=20 },
        Opsitheiel  = { hiMin=22, hiMax=30, loMin=10, loMax=16, humMin=5,  humMax=25 }
    },
     ["Cold Steppe"] = {
        Atosiel     = { hiMin=10, hiMax=18, loMin=2,  loMax=8,  humMin=30, humMax=50 },
        Thalassiel  = { hiMin=20, hiMax=28, loMin=10, loMax=15, humMin=25, humMax=45 },
        Opsitheiel  = { hiMin=0,  hiMax=7,  loMin=-6, loMax=0,  humMin=35, humMax=55 }
    },
     ["Hot Steppe"] = {
         Atosiel    = { hiMin=23, hiMax=30, loMin=12, loMax=18, humMin=20, humMax=40 },
        Thalassiel  = { hiMin=30, hiMax=40, loMin=20, loMax=25, humMin=15, humMax=35 },
         Opsitheiel  = { hiMin=25, hiMax=33, loMin=15, loMax=20, humMin=15, humMax=40 }
    },
     ["Subarctic"] = {
        Atosiel     = { hiMin=0,  hiMax=8,  loMin=-10,loMax=-1, humMin=50, humMax=80 },
        Thalassiel  = { hiMin=5,  hiMax=15, loMin=-1, loMax=5,  humMin=50, humMax=85 },
         Opsitheiel  = { hiMin=-5, hiMax=0,  loMin=-15,loMax=-5, humMin=60, humMax=90 }
    }
}
}


---------------------------------------------------------
---------------------------------------------------------
-- 5. getEventColor
-- 6. Check Forecast -> Append Extra Hazard Messages
---------------------------------------------------------
---------------------------------------------------------
local function getAdvisory(cityName, forecastStr)
    local baseAdvisory = cityDisasters[cityName] or "No typical hazards"
    local textLower = forecastStr:lower()


local function getEventColor(eventText)
    local extra = {}
     local textLower = eventText:lower()
     -- Storm watch
     if textLower:find("thunder") or textLower:find("storm") then
     if textLower:find("storm") or textLower:find("thunder") then
         return "#FFD2D2"
         table.insert(extra, "Storm watch in effect")
     elseif textLower:find("snow") or textLower:find("sleet") or textLower:find("flurries") then
    end
         return "#D2ECFF"
    -- Snow hazard
     elseif textLower:find("rain") or textLower:find("drizzle") or textLower:find("downpour") then
     if textLower:find("snow") or textLower:find("sleet") or textLower:find("flurries") then
         return "#D2DFFF"
         table.insert(extra, "Snow hazard")
     elseif textLower:find("dust") or textLower:find("desert") then
    end
         return "#FFFACD"
    -- Dust advisory
     if textLower:find("dust") or textLower:find("desert") then
        table.insert(extra, "Dust advisory")
    end
    -- Flash flood
    if textLower:find("downpour") then
         table.insert(extra, "Flash flood possible")
    end
     -- Fog or mist
    if textLower:find("fog") or textLower:find("mist") then
        table.insert(extra, "Low visibility advisory")
    end
 
    if #extra > 0 then
         return baseAdvisory .. "; " .. table.concat(extra, "; ")
     else
     else
         return "#F8F8F8"
         return baseAdvisory
     end
     end
end
end


---------------------------------------------------------
---------------------------------------------------------
-- 6. getRandomWeatherStats
-- 7. Convert °C -> °F
---------------------------------------------------------
---------------------------------------------------------
local function cToF(c)
    return math.floor(c * 9/5 + 32 + 0.5)
end


---------------------------------------------------------
-- 8. Random Weather Stats
---------------------------------------------------------
local windDirections = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}
local windDirections = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}


Line 460: Line 480:
     local lo  = math.random(data.loMin, data.loMax)
     local lo  = math.random(data.loMin, data.loMax)
     local hum  = math.random(data.humMin, data.humMax)
     local hum  = math.random(data.humMin, data.humMax)
 
     local cRain= math.random(0,100)
     local cRain = math.random(0,100)
     local wDir = windDirections[math.random(#windDirections)]
     local wDir = windDirections[math.random(#windDirections)]
     local wSpd = math.random(0,50)
     local wSpd = math.random(0,50)


     return {
     return {
Line 476: Line 495:


---------------------------------------------------------
---------------------------------------------------------
-- 7. Celsius -> Fahrenheit conversion
-- 9. Determine Cell Color based on keywords in the event
---------------------------------------------------------
---------------------------------------------------------
 
local function getEventColor(eventText)
local function cToF(c)
    local textLower = eventText:lower()
     return math.floor(c * 9/5 + 32 + 0.5)
     if textLower:find("thunder") or textLower:find("storm") then
        return "#FFD2D2"
    elseif textLower:find("snow") or textLower:find("sleet") or textLower:find("flurries") then
        return "#D2ECFF"
    elseif textLower:find("rain") or textLower:find("drizzle") or textLower:find("downpour") then
        return "#D2DFFF"
    elseif textLower:find("dust") or textLower:find("desert") then
        return "#FFFACD"
    else
        return "#F8F8F8"
    end
end
end


---------------------------------------------------------
---------------------------------------------------------
-- 8. City Data (unchanged)
-- 10. City Data
---------------------------------------------------------
---------------------------------------------------------
local cityData = {
local cityData = {
     {city = "Vaeringheim",      climate = "Humid Subtropical"},
     {city = "Vaeringheim",      climate = "Humid Subtropical"},
Line 498: Line 526:
     {city = "Lunalis Sancta",    climate = "Oceanic"},
     {city = "Lunalis Sancta",    climate = "Oceanic"},
     {city = "Sylvapolis",        climate = "Humid Subtropical"},
     {city = "Sylvapolis",        climate = "Humid Subtropical"},
     {city = "Saluria",          climate = "Oceanic"},
     {city = "Saluria",          climate = "Oceanic"},
     {city = "Aetherium",        climate = "Subarctic"},
     {city = "Aetherium",        climate = "Subarctic"},
Line 508: Line 535:
     {city = "Koinonía",          climate = "Oceanic"},
     {city = "Koinonía",          climate = "Oceanic"},
     {city = "Aureum",            climate = "Mediterranean (Hot Summer)"},
     {city = "Aureum",            climate = "Mediterranean (Hot Summer)"},
     {city = "Skýrophos",        climate = "Oceanic"},
     {city = "Skýrophos",        climate = "Oceanic"},
     {city = "Bjornopolis",      climate = "Oceanic"},
     {city = "Bjornopolis",      climate = "Oceanic"},
Line 514: Line 540:
     {city = "Norsolyra",        climate = "Oceanic"},
     {city = "Norsolyra",        climate = "Oceanic"},
     {city = "Thorsalon",        climate = "Oceanic"},
     {city = "Thorsalon",        climate = "Oceanic"},
     {city = "Pelagia",          climate = "Hot Steppe"},
     {city = "Pelagia",          climate = "Hot Steppe"},
     {city = "Myrene",            climate = "Oceanic"},
     {city = "Myrene",            climate = "Oceanic"},
Line 520: Line 545:
     {city = "Ephyra",            climate = "Subpolar Oceanic"},
     {city = "Ephyra",            climate = "Subpolar Oceanic"},
     {city = "Halicarn",          climate = "Mediterranean (Hot Summer)"},
     {city = "Halicarn",          climate = "Mediterranean (Hot Summer)"},
     {city = "Keybir-Aviv",      climate = "Humid Subtropical"},
     {city = "Keybir-Aviv",      climate = "Humid Subtropical"},
     {city = "Tel-Amin",          climate = "Mediterranean (Hot Summer)"},
     {city = "Tel-Amin",          climate = "Mediterranean (Hot Summer)"},
Line 526: Line 550:
     {city = "Jogi",              climate = "Oceanic"},
     {city = "Jogi",              climate = "Oceanic"},
     {city = "Lewisburg",        climate = "Humid Subtropical"},
     {city = "Lewisburg",        climate = "Humid Subtropical"},
     {city = "Thermosalem",      climate = "Oceanic"},
     {city = "Thermosalem",      climate = "Oceanic"},
     {city = "Akróstadium",      climate = "Cold Steppe"},
     {city = "Akróstadium",      climate = "Cold Steppe"},
Line 534: Line 557:


---------------------------------------------------------
---------------------------------------------------------
-- 9. Base Disasters (typical hazards)
-- 11. The main weather forecast function
--    Automatically updates daily without manual intervention.
---------------------------------------------------------
---------------------------------------------------------
local cityDisasters = {
    ["Vaeringheim"]      = "Seasonal storms and lake-driven floods",
    ["Luminaria"]        = "River floods during heavy rains",
    ["Serena"]            = "Snowstorms at higher elevations",
    ["Pyralis"]          = "Occasional steam vent eruptions",
    ["Symphonara"]        = "Landslides on steep slopes",
    ["Aurelia"]          = "Droughts and brushfires",
    ["Somniumpolis"]      = "Recurrent flooding in marshes",
    ["Nexa"]              = "Localized mudslides",
    ["Lunalis Sancta"]    = "Fog-related travel hazards",
    ["Sylvapolis"]        = "Swamp flooding",
    ["Saluria"]          = "River floods",
    ["Aetherium"]        = "Blizzards",
    ["Ferrum Citadel"]    = "Dust storms and heatwaves",
    ["Acheron"]          = "Occasional flash floods",
    ["Erythros"]          = "Tar-pit gas releases",
    ["Catonis Atrium"]    = "Landslides on steep slopes",
    ["Delphica"]          = "Coastal storms",
    ["Koinonía"]          = "Mild landslides",
    ["Aureum"]            = "Summer wildfires",
    ["Skýrophos"]        = "Cliff erosion and sea storms",
    ["Bjornopolis"]      = "Flood surges near waterfalls",
    ["Aegirheim"]        = "Coastal gales, blizzards",
    ["Norsolyra"]        = "Marsh flooding",
    ["Thorsalon"]        = "Occasional cliff collapses",
    ["Pelagia"]          = "Sandstorms",
    ["Myrene"]            = "Minor landslides",
    ["Thyrea"]            = "Lake overflows, marsh flooding",
    ["Ephyra"]            = "Avalanches in higher passes",
    ["Halicarn"]          = "Occasional flash floods",
    ["Keybir-Aviv"]      = "Shoreline flooding",
    ["Tel-Amin"]          = "Wildfires in dry spells",
    ["Diamandis"]        = "Droughts",
    ["Jogi"]              = "River floods",
    ["Lewisburg"]        = "Swamp overflows",
    ["Thermosalem"]      = "Occasional landslides near hot springs",
    ["Akróstadium"]      = "Dust devils on dry slopes",
    ["Sufriya"]          = "Storm surges from inlet",
    ["Lykopolis"]        = "Mine collapses, gas leaks"
}
---------------------------------------------------------
-- 10. Disaster Logic based on Weather
-- If the forecast text includes certain words (e.g. "storm"),
-- we append an extra note to the base advisory.
---------------------------------------------------------
local function getAdvisory(cityName, forecastStr)
    local baseAdvisory = cityDisasters[cityName] or "No typical hazards"
    local textLower = forecastStr:lower()
    local extra = {}
    -- If forecast mentions storms, add "Storm watch in effect"
    if textLower:find("storm") or textLower:find("thunder") then
        table.insert(extra, "Storm watch in effect")
    end
    -- If forecast mentions "snow", "sleet", or "flurries", add "Snow hazard"
    if textLower:find("snow") or textLower:find("sleet") or textLower:find("flurries") then
        table.insert(extra, "Snow hazard")
    end
    -- If forecast mentions "dust" or "desert", add "Dust advisory"
    if textLower:find("dust") or textLower:find("desert") then
        table.insert(extra, "Dust advisory")
    end
    -- If forecast mentions "heavy downpour" or "downpour", add "Flash flood possible"
    if textLower:find("downpour") then
        table.insert(extra, "Flash flood possible")
    end
    -- If forecast mentions "fog", add "Low visibility"
    if textLower:find("fog") or textLower:find("mist") then
        table.insert(extra, "Low visibility advisory")
    end
    if #extra > 0 then
        return baseAdvisory .. "; " .. table.concat(extra, "; ")
    else
        return baseAdvisory
    end
end
---------------------------------------------------------
-- 11. Main Weather Forecast Table
---------------------------------------------------------
function p.weatherForecast(frame)
function p.weatherForecast(frame)
     local dateInfo  = getCurrentDateInfo()
     local dateInfo  = getCurrentDateInfo()
Line 636: Line 571:
         dayOfYear, yearNumber, seasonName))
         dayOfYear, yearNumber, seasonName))


     -- Begin table with "Natural Disaster Advisory" column
     -- Create the table header
     table.insert(output,
     table.insert(output,
         '{| class="wikitable sortable" style="width:100%; text-align:left;"\n'
         '{| class="wikitable sortable" style="width:100%; text-align:left;"\n'
Line 645: Line 580:
     )
     )


    -- Generate a row for each city
     for _, cityEntry in ipairs(cityData) do
     for _, cityEntry in ipairs(cityData) do
         local cityName    = cityEntry.city
         local cityName    = cityEntry.city or "Unknown City"
         local climateName = cityEntry.climate
         local climateName = cityEntry.climate or "N/A"


         -- 1) Determine random weather event
         -- 1) Get random weather event
         local cTable    = climateEvents[climateName]
         local climateTable = climateEvents[climateName]
         local seasonTbl = cTable and cTable[seasonName]
         local seasonTable  = climateTable and climateTable[seasonName]
         local forecastStr = "No data"
         local forecastStr = "No data"
         if seasonTbl and #seasonTbl > 0 then
         if seasonTable and #seasonTable > 0 then
             local rndIndex = math.random(#seasonTbl)
             local rndIndex = math.random(#seasonTable)
             forecastStr = seasonTbl[rndIndex]
             forecastStr = seasonTable[rndIndex]
         end
         end


         -- 2) Color-coded cell by event keywords
         -- 2) Determine color based on keywords
         local rowColor = getEventColor(forecastStr)
         local rowColor = getEventColor(forecastStr)


         -- 3) Random stats (in °C behind the scenes; displayed in °F)
         -- 3) Generate random stats (hi/lo in °C, but displayed °F)
         local stats  = getRandomWeatherStats(climateName, seasonName)
         local stats  = getRandomWeatherStats(climateName, seasonName)
         local hiC    = stats.high
         local hiC    = stats.high
Line 673: Line 609:
         local loF = (type(loC)=="number") and cToF(loC) or loC
         local loF = (type(loC)=="number") and cToF(loC) or loC


         -- 4) Determine advisory text by city + weather
         -- 4) Combine base hazards with forecast triggers
         local advisory = getAdvisory(cityName, forecastStr)
         local advisory = getAdvisory(cityName, forecastStr)


        -- 5) Insert row
         table.insert(output, "|-\n")
         table.insert(output, "|-\n")
         table.insert(output, string.format(
         table.insert(output, string.format(
[[| %s || %s || %s || %s || %s || %s || %s || %s || %s || style="background-color:%s" | %s || %s
[[| %s || %s || %s || %s || %s || %s || %s || %s || %s || style="background-color:%s" | %s || %s
]],
]],
             cityName,
             cityName,       -- city
             climateName,
             climateName,   -- climate
             seasonName,
             seasonName,     -- season
             tostring(hiF),
             tostring(hiF), -- high °F
             tostring(loF),
             tostring(loF), -- low °F
             tostring(humidity),
             tostring(humidity),
             tostring(cRain),
             tostring(cRain),

Revision as of 18:35, 26 December 2024

Documentation for this module may be created at Module:BassaridiaForecast/doc

---------------------------------------------------------
-- Module:WeatherForecastTable
-- Generates a fully updated daily forecast table with:
--  • Random weather factors for each city, seeded by os.time()
--  • PSSC date logic (Atosiel, Thalassiel, Opsitheiel)
--  • All 8 spelled-out climates × 3 seasons × 10 events each
--  • All major & minor cities in Bassaridia Vaeringheim,
--    New South Jangsong, and Haifan Bassaridia
--  • High/Low in Celsius behind the scenes, displayed in °F only
--  • Humidity, chance of rain, wind direction, wind speed
--  • Color-coded "Today's Weather" cell by event keywords
--  • Natural Disaster Advisory merges each city's typical hazards
--    with any triggered by today's weather text (storm, dust, etc.)
--  • No numeric checks or extra error handling
---------------------------------------------------------

local p = {}

---------------------------------------------------------
-- 0. Random Seed
-- Ensures new random results every day or invocation.
---------------------------------------------------------
math.randomseed(os.time())

---------------------------------------------------------
-- 1. PSSC Calendar System
---------------------------------------------------------
local function getCurrentDateInfo()
    local startDate = os.time({year = 1999, month = 8, day = 6})
    local secondsInDay = 86400
    local daysPerYear = 183

    local currentTime = os.time()
    local totalDaysElapsed = math.floor((currentTime - startDate) / secondsInDay)

    local yearFraction = totalDaysElapsed / daysPerYear
    local psscYear = math.floor(yearFraction)
    local dayOfYear = math.floor((yearFraction - psscYear) * daysPerYear) + 1

    return {
        psscYear = psscYear,
        dayOfYear = dayOfYear
    }
end

---------------------------------------------------------
-- 2. Determine Season
-- (Atosiel = days 1..61; Thalassiel = 62..122; Opsitheiel = 123..183)
---------------------------------------------------------
local function getSeasonName(dayOfYear)
    if dayOfYear <= 61 then
        return "Atosiel"
    elseif dayOfYear <= 122 then
        return "Thalassiel"
    else
        return "Opsitheiel"
    end
end

---------------------------------------------------------
-- 3. Weather Events Table (8 climates × 3 seasons × 10 events)
---------------------------------------------------------
local climateEvents = {
    ["Humid Subtropical"] = {
        Atosiel = {
            "Morning drizzle and warm afternoon sunshine",
            "Mild thunderstorm building by midday",
            "Patchy fog at dawn, clearing toward lunch",
            "Light rain with sunny breaks after noon",
            "Gentle breezes, blossoming warmth, low humidity",
            "Scattered clouds with a brief shower by dusk",
            "Humid sunrise, comfortable high around midday",
            "Overcast for part of the day, mild temperatures",
            "Warm breezes carrying faint floral scents",
            "Partial sun, warm with a slight chance of rain"
        },
        Thalassiel = {
            "Hot, steamy day with intense midday heat",
            "Tropical-like humidity, afternoon thunder possible",
            "Intermittent heavy downpours, muggy evenings",
            "High humidity and patchy thunderstorms late",
            "Sun-scorched morning, scattered storms by dusk",
            "Hazy sunshine, extremely warm all day",
            "Thick humidity, chance of lightning late evening",
            "Sticky air, short downpours in isolated spots",
            "Heat advisory with only brief cooling at night",
            "Nighttime storms lingering into early morning"
        },
        Opsitheiel = {
            "Warm daytime, gentle evening breezes",
            "Occasional rain, otherwise mild temperatures",
            "Late-season warmth, scattered rain after sunset",
            "Cooler mornings, returning to warmth by midday",
            "Sparse cloud cover, tranquil weather overall",
            "Fog at dawn, warm midday, pleasant night",
            "Partial sun, comfortable humidity levels",
            "Evening drizzle with mild breezes",
            "Patchy haze, moderate warmth throughout the day",
            "Short-lived shower, then clearing skies"
        }
    },
    ["Oceanic"] = {
        Atosiel = {
            "Frequent light rain, cool breezes all day",
            "Foggy dawn, mild midmorning sunshine",
            "Short sunbreaks among passing showers",
            "Consistent drizzle, fresh winds from the sea",
            "Cloudy intervals with a few bright spells",
            "Late-afternoon clearing, crisp evening air",
            "Slow-moving clouds, mild temperatures",
            "Gentle but persistent rain, green foliage thriving",
            "Off-and-on showers, brief sunny interludes",
            "Steady breeze, moderate humidity levels"
        },
        Thalassiel = {
            "Light rain off and on, mild temperatures",
            "Overcast with comfortable breezes throughout",
            "Drizzly morning, partly cloudy afternoon",
            "Soft rains, lush vegetation, stable temps",
            "Cool, damp start, drying toward evening",
            "Frequent cloud cover, gentle summer breeze",
            "Moist air with lingering fog near streams",
            "Rain-laden air, occasional breaks of sun",
            "Maritime winds bringing light spray inland",
            "Cloudy midday, mild sunshine before dusk"
        },
        Opsitheiel = {
            "Overcast skies, cool drizzle through the day",
            "Sporadic showers, chillier in the evening",
            "Low visibility in morning fog, slow clearing",
            "Gray skies, frequent rain squalls, cool wind",
            "Chilly nightfall, damp ground all day",
            "Heavier showers arriving late afternoon",
            "Periodic drizzle, temperatures on the cool side",
            "Morning gloom, occasional pockets of clearing",
            "Evening rainfall pushing in from the coast",
            "Dense cloud cover, breezy and damp"
        }
    },
    ["Subpolar Oceanic"] = {
        Atosiel = {
            "Near-freezing dawn, cold drizzle by midday",
            "Mist over melting snow patches, breezy afternoon",
            "Overcast skies, mix of rain and sleet",
            "Cool, damp air, slight warmup after noon",
            "Late-day sleet turning to light rain",
            "Mountaintop flurries, valley drizzle",
            "Cloudy morning, partial clearing in late afternoon",
            "Chilly breeze, scattered showers off and on",
            "Gray skies, some slushy buildup on paths",
            "Snowmelt water raising local streams"
        },
        Thalassiel = {
            "Cool, short days with periodic drizzle",
            "Heavy low clouds, pockets of bright breaks",
            "Gentle rain, evening chill deeper than normal",
            "Intermittent showers, damp wind from hills",
            "Cloud deck lingering, occasional lighter drizzle",
            "Faint sunlight overshadowed by thick cloud",
            "Subdued warmth, sporadic mist across ridges",
            "Surprisingly bright morning, clouding by dusk",
            "Short bursts of rain followed by fog",
            "Late-night chill with drizzle or brief sleet"
        },
        Opsitheiel = {
            "Steady cold rain mixing with wet snow",
            "Freezing drizzle at dawn, raw gusty winds",
            "Snowfall likely at higher elevations, rain below",
            "Cloudy, damp day with potential sleet storms",
            "Early morning frost turning to slush midday",
            "Occasional heavy showers with flurry bursts",
            "Gray gloom, subfreezing nights across valleys",
            "Pelting sleet for an hour, then calm, cold air",
            "Gusty evening, possible snow accumulations",
            "Sun rarely visible, persistent winter gloom"
        }
    },
    ["Mediterranean (Hot Summer)"] = {
        Atosiel = {
            "Mild temperatures, bright sunshine, dry air",
            "Morning dew, warming fast under clear skies",
            "Cool breezes off the sea, comfortable afternoon",
            "Sunny midday with a crisp, light wind",
            "Short drizzly spell, then mostly clear",
            "Early bloom across hills, moderate warmth",
            "Mostly sunny, a few scattered clouds late",
            "Light shower possible at sunrise, drying by noon",
            "Warming trend, low humidity, pleasant day",
            "Gradual warming under spotless sky"
        },
        Thalassiel = {
            "Very hot midday sun, minimal clouds",
            "Scorching days, slight breeze at dusk",
            "Parched hillsides, no sign of rainfall",
            "High UV index, bright, glaring sunlight",
            "Coastal dryness, strong midday glare",
            "Overnight relief, but intense heat returns early",
            "Dust in the wind from inland hills",
            "Cloudless sky, near-record high temps",
            "Salt-laden breezes if near the coast, scorching inland",
            "Heatwaves persisting, zero rain expected"
        },
        Opsitheiel = {
            "Cooler spells, brief showery intervals",
            "Cloudy periods bringing mild relief from heat",
            "Pleasant afternoons, occasional dusk rains",
            "Moderate days, crisp mornings, calm nights",
            "Sporadic light rainfall, refreshing breezes",
            "Cloudbanks drifting inland, mild drizzle at times",
            "Patchy overcast, comfortable midday temps",
            "Clear dawn, mild sunshine, gentle wind late",
            "Intervals of cloud cover, potential short rain",
            "Moist sea air, moderate daytime warmth"
        }
    },
    ["Hot Desert"] = {
        Atosiel = {
            "Hot afternoons, cooler late nights, wide temp swing",
            "Dry air, bright sunshine, no clouds in sight",
            "Gentle breezes raising light sand by midday",
            "Evening chill setting in after hot daytime",
            "Minor dust devil scouring the dunes",
            "Visibility excellent, stable high pressure",
            "Patchy desert haze, strong sun overhead",
            "No hint of precipitation, cloudless horizon",
            "Daytime warmth, refreshing if slight breeze arrives",
            "Sun-warmed rock surfaces, mild nights"
        },
        Thalassiel = {
            "Extreme heat from mid-morning onward",
            "Blistering midday sun, risk of heat stroke",
            "Near-record highs, swirling dust at times",
            "Virtually no clouds, scorching open sands",
            "Occasional dust storm cutting visibility briefly",
            "Mirage-like shimmer across flat terrain",
            "Sunset brings partial relief, still quite warm",
            "Dry conditions, subpar humidity all day",
            "Baking desert floor, potential for blowing sand",
            "Intense heat building day after day"
        },
        Opsitheiel = {
            "Warm, mostly sunny with cooler nights",
            "Sparse winds carrying fine sand sporadically",
            "Large day-night temperature gap, no precipitation",
            "Stable conditions, sunlit afternoons, brisk evenings",
            "Mildly hot days, star-filled clear skies at night",
            "Shallow dust clouds after brief winds",
            "Occasional gust picking up desert grit",
            "Gentle warmth, dryness prevalent, no clouds",
            "Cool breezes shortly after sunset, mild day overall",
            "Hazy horizon, soft morning glow across dunes"
        }
    },
    ["Cold Steppe"] = {
        Atosiel = {
            "Cool mornings, moderate midday warmth, breezy",
            "Light rain passing through grasslands midday",
            "Variable cloud cover, mild temperature swings",
            "Patchy frost at dawn, warming soon after",
            "Crisp air, possible small hail if storms appear",
            "Sunny afternoon, cooler late evening",
            "Gentle breeze, fleeting sun amidst scattered clouds",
            "Slow temperature rise, slight dryness in mid-afternoon",
            "Brief drizzle, otherwise bright and breezy",
            "Day-night difference noticeable, mild but windy"
        },
        Thalassiel = {
            "Warm day, potential for gusty thunderstorms",
            "Hot midday sun, dryness intensifying by late day",
            "Cloud buildup, short but intense showers possible",
            "Clear morning, chance of late afternoon storms",
            "Long daylight hours, rolling thunder near dusk",
            "Slight dryness, patchy heat with limited shade",
            "Periodic storms bringing relief from heat",
            "Warm evening, slight nighttime cooldown",
            "Sky remains mostly clear, grassland shimmering",
            "Thunderheads visible in distance, might pass by"
        },
        Opsitheiel = {
            "Cool to cold days, frosty nights on open steppe",
            "Possible light snowfall, especially overnight",
            "Wind-driven chill under gray skies",
            "Sparse precipitation, dryness persists, cold air",
            "Subfreezing after sunset, sometimes sunny midday",
            "Short bursts of sunshine, otherwise chilly conditions",
            "Occasional dusting of snow, quickly melting by noon",
            "Biting wind, few clouds, stark horizon",
            "Clearing late morning, crisp, cold nightfall",
            "Daytime near freezing, nights well below"
        }
    },
    ["Hot Steppe"] = {
        Atosiel = {
            "Hot daytime sun, slight breeze, no rain",
            "Gusty wind with dust swirling near midday",
            "Warm mornings, scorching afternoon, very low humidity",
            "Light breeze after sundown, starry overhead",
            "Some haze from heated ground, minimal cloud cover",
            "Sun intensity rising toward midday peak",
            "Dry soil conditions, no sign of moisture",
            "Sparse vegetation, daily heat climbing gradually",
            "Clear horizon, wind picking up in late evening",
            "Sun exposure high, consistent dryness"
        },
        Thalassiel = {
            "Brutally hot midday sun, patchy dust storms",
            "Scorching conditions, faint breeze offers minimal relief",
            "Occasional swirling wind gusts, drifting dust",
            "Heated ground emits rippling mirages at distance",
            "Persistent dryness, minimal nighttime cooldown",
            "Skies remain cloudless, high evaporation rate",
            "Dust-laden air in late afternoon swirl",
            "Rare cloud can appear but quickly vanishes",
            "Daily highs remain extreme, nights only mild",
            "Lingering warmth through sunset, dryness unwavering"
        },
        Opsitheiel = {
            "Hot days, moderate evenings, stable dryness",
            "Rare short rains if storm fronts approach, mostly none",
            "Daytime heat lingering, nights slightly cooler",
            "Periodically hazy morning from airborne dust",
            "Mild breezes, daytime remains intensely hot",
            "Cloudless skies, gentle drop in temps overnight",
            "Dust devils possible over parched plains",
            "Occasional relief from mild wind, no precipitation",
            "Hot, tranquil afternoon, moderate wind at dusk",
            "Minimal cloud presence, dryness dominating environment"
        }
    },
    ["Subarctic"] = {
        Atosiel = {
            "Snow melting, slushy paths, daytime sunshine",
            "Chilly breezes, frequent flurry patches possible",
            "Long nights gradually shortening, crisp mornings",
            "Mixed precipitation, cold rain at lower altitudes",
            "Slush build-up midmorning, partial sun midday",
            "Sunny breaks around noon, subzero by late night",
            "Sporadic storm with sleet or melting snow",
            "Icy patches linger, overall chilly but bright",
            "Early thaw, mild midday, returning chill after dusk",
            "Reluctant spring with freezing nights, slow warm days"
        },
        Thalassiel = {
            "Short, cool days, moderate sunshine at times",
            "Rainy intervals, potential sleet in highest peaks",
            "Snow line retreating, green valleys emerging slowly",
            "Extended twilight, crisp air after sundown",
            "Sudden midafternoon chill despite mid-summer period",
            "Drizzle commonly, heavier rainfall occasionally",
            "Mountain passes remain cool, breezy conditions",
            "Mostly cloudy, occasional glimpses of sun",
            "Brisk wind, earlier nightfall than lower latitudes",
            "Daytime highs remain mild, nights quite cold"
        },
        Opsitheiel = {
            "Early snowfall returning, freezing ground rapidly",
            "Prolonged darkness, bitterness sets in quickly",
            "Gusty winds carrying ice crystals through valleys",
            "Heavy drifts forming, multiple snowfall events",
            "Frequent subzero lows, no hint of thaw",
            "Blizzard-like conditions with large snow accumulations",
            "Icy rivers, widespread frost in daylight",
            "Mountains see near-constant snow, valleys freeze nightly",
            "Rare clear spells, intense wind chill outside",
            "Deep winter mode, swirling snow flurries all day"
        }
    }
}

---------------------------------------------------------
-- 5. Typical Disasters for Each City
---------------------------------------------------------
local cityDisasters = {
    ["Vaeringheim"]       = "Seasonal storms and lake-driven floods",
    ["Luminaria"]         = "River floods during heavy rains",
    ["Serena"]            = "Snowstorms at higher elevations",
    ["Pyralis"]           = "Occasional steam vent eruptions",
    ["Symphonara"]        = "Landslides on steep slopes",
    ["Aurelia"]           = "Droughts and brushfires",
    ["Somniumpolis"]      = "Recurrent flooding in marshes",
    ["Nexa"]              = "Localized mudslides",
    ["Lunalis Sancta"]    = "Fog-related travel hazards",
    ["Sylvapolis"]        = "Swamp flooding",
    ["Saluria"]           = "River floods",
    ["Aetherium"]         = "Blizzards",
    ["Ferrum Citadel"]    = "Dust storms and heatwaves",
    ["Acheron"]           = "Occasional flash floods",
    ["Erythros"]          = "Tar-pit gas releases",
    ["Catonis Atrium"]    = "Landslides on steep slopes",
    ["Delphica"]          = "Coastal storms",
    ["Koinonía"]          = "Mild landslides",
    ["Aureum"]            = "Summer wildfires",

    ["Skýrophos"]         = "Cliff erosion and sea storms",
    ["Bjornopolis"]       = "Flood surges near waterfalls",
    ["Aegirheim"]         = "Coastal gales, blizzards",
    ["Norsolyra"]         = "Marsh flooding",
    ["Thorsalon"]         = "Occasional cliff collapses",

    ["Pelagia"]           = "Sandstorms",
    ["Myrene"]            = "Minor landslides",
    ["Thyrea"]            = "Lake overflows, marsh flooding",
    ["Ephyra"]            = "Avalanches in higher passes",
    ["Halicarn"]          = "Occasional flash floods",

    ["Keybir-Aviv"]       = "Shoreline flooding",
    ["Tel-Amin"]          = "Wildfires in dry spells",
    ["Diamandis"]         = "Droughts",
    ["Jogi"]              = "River floods",
    ["Lewisburg"]         = "Swamp overflows",

    ["Thermosalem"]       = "Occasional landslides near hot springs",
    ["Akróstadium"]       = "Dust devils on dry slopes",
    ["Sufriya"]           = "Storm surges from inlet",
    ["Lykopolis"]         = "Mine collapses, gas leaks"
}

---------------------------------------------------------
-- 6. Check Forecast -> Append Extra Hazard Messages
---------------------------------------------------------
local function getAdvisory(cityName, forecastStr)
    local baseAdvisory = cityDisasters[cityName] or "No typical hazards"
    local textLower = forecastStr:lower()

    local extra = {}
    -- Storm watch
    if textLower:find("storm") or textLower:find("thunder") then
        table.insert(extra, "Storm watch in effect")
    end
    -- Snow hazard
    if textLower:find("snow") or textLower:find("sleet") or textLower:find("flurries") then
        table.insert(extra, "Snow hazard")
    end
    -- Dust advisory
    if textLower:find("dust") or textLower:find("desert") then
        table.insert(extra, "Dust advisory")
    end
    -- Flash flood
    if textLower:find("downpour") then
        table.insert(extra, "Flash flood possible")
    end
    -- Fog or mist
    if textLower:find("fog") or textLower:find("mist") then
        table.insert(extra, "Low visibility advisory")
    end

    if #extra > 0 then
        return baseAdvisory .. "; " .. table.concat(extra, "; ")
    else
        return baseAdvisory
    end
end

---------------------------------------------------------
-- 7. Convert °C -> °F
---------------------------------------------------------
local function cToF(c)
    return math.floor(c * 9/5 + 32 + 0.5)
end

---------------------------------------------------------
-- 8. Random Weather Stats
---------------------------------------------------------
local windDirections = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}

local function getRandomWeatherStats(climate, season)
    local data = climateTemperature[climate] and climateTemperature[climate][season]
    if not data then
        return {
            high = "N/A",
            low = "N/A",
            humidity = "N/A",
            chanceOfRain = "N/A",
            windDir = "N/A",
            windSpeed = "N/A"
        }
    end

    local hi   = math.random(data.hiMin, data.hiMax)
    local lo   = math.random(data.loMin, data.loMax)
    local hum  = math.random(data.humMin, data.humMax)
    local cRain= math.random(0,100)
    local wDir = windDirections[math.random(#windDirections)]
    local wSpd = math.random(0,50)

    return {
        high        = hi,
        low         = lo,
        humidity    = hum,
        chanceOfRain= cRain,
        windDir     = wDir,
        windSpeed   = wSpd
    }
end

---------------------------------------------------------
-- 9. Determine Cell Color based on keywords in the event
---------------------------------------------------------
local function getEventColor(eventText)
    local textLower = eventText:lower()
    if textLower:find("thunder") or textLower:find("storm") then
        return "#FFD2D2"
    elseif textLower:find("snow") or textLower:find("sleet") or textLower:find("flurries") then
        return "#D2ECFF"
    elseif textLower:find("rain") or textLower:find("drizzle") or textLower:find("downpour") then
        return "#D2DFFF"
    elseif textLower:find("dust") or textLower:find("desert") then
        return "#FFFACD"
    else
        return "#F8F8F8"
    end
end

---------------------------------------------------------
-- 10. City Data
---------------------------------------------------------
local cityData = {
    {city = "Vaeringheim",       climate = "Humid Subtropical"},
    {city = "Luminaria",         climate = "Oceanic"},
    {city = "Serena",            climate = "Subpolar Oceanic"},
    {city = "Pyralis",           climate = "Oceanic"},
    {city = "Symphonara",        climate = "Oceanic"},
    {city = "Aurelia",           climate = "Mediterranean (Hot Summer)"},
    {city = "Somniumpolis",      climate = "Humid Subtropical"},
    {city = "Nexa",              climate = "Oceanic"},
    {city = "Lunalis Sancta",    climate = "Oceanic"},
    {city = "Sylvapolis",        climate = "Humid Subtropical"},
    {city = "Saluria",           climate = "Oceanic"},
    {city = "Aetherium",         climate = "Subarctic"},
    {city = "Ferrum Citadel",    climate = "Hot Desert"},
    {city = "Acheron",           climate = "Cold Steppe"},
    {city = "Erythros",          climate = "Oceanic"},
    {city = "Catonis Atrium",    climate = "Oceanic"},
    {city = "Delphica",          climate = "Oceanic"},
    {city = "Koinonía",          climate = "Oceanic"},
    {city = "Aureum",            climate = "Mediterranean (Hot Summer)"},
    {city = "Skýrophos",         climate = "Oceanic"},
    {city = "Bjornopolis",       climate = "Oceanic"},
    {city = "Aegirheim",         climate = "Subarctic"},
    {city = "Norsolyra",         climate = "Oceanic"},
    {city = "Thorsalon",         climate = "Oceanic"},
    {city = "Pelagia",           climate = "Hot Steppe"},
    {city = "Myrene",            climate = "Oceanic"},
    {city = "Thyrea",            climate = "Humid Subtropical"},
    {city = "Ephyra",            climate = "Subpolar Oceanic"},
    {city = "Halicarn",          climate = "Mediterranean (Hot Summer)"},
    {city = "Keybir-Aviv",       climate = "Humid Subtropical"},
    {city = "Tel-Amin",          climate = "Mediterranean (Hot Summer)"},
    {city = "Diamandis",         climate = "Mediterranean (Hot Summer)"},
    {city = "Jogi",              climate = "Oceanic"},
    {city = "Lewisburg",         climate = "Humid Subtropical"},
    {city = "Thermosalem",       climate = "Oceanic"},
    {city = "Akróstadium",       climate = "Cold Steppe"},
    {city = "Sufriya",           climate = "Humid Subtropical"},
    {city = "Lykopolis",         climate = "Oceanic"}
}

---------------------------------------------------------
-- 11. The main weather forecast function
--    Automatically updates daily without manual intervention.
---------------------------------------------------------
function p.weatherForecast(frame)
    local dateInfo   = getCurrentDateInfo()
    local dayOfYear  = dateInfo.dayOfYear
    local yearNumber = dateInfo.psscYear
    local seasonName = getSeasonName(dayOfYear)

    local output = {}
    table.insert(output, "== Daily Weather Forecast ==\n")
    table.insert(output, string.format("''(Day %d of Year %d PSSC, %s)''\n\n",
        dayOfYear, yearNumber, seasonName))

    -- Create the table header
    table.insert(output,
        '{| class="wikitable sortable" style="width:100%; text-align:left;"\n'
    )
    table.insert(output,
[[! City !! Climate !! Season !! High °F !! Low °F !! Humidity (%) !! Chance of Rain (%) !! Wind Direction !! Wind Speed (km/h) !! Today's Weather !! Natural Disaster Advisory
]]
    )

    -- Generate a row for each city
    for _, cityEntry in ipairs(cityData) do
        local cityName    = cityEntry.city or "Unknown City"
        local climateName = cityEntry.climate or "N/A"

        -- 1) Get random weather event
        local climateTable = climateEvents[climateName]
        local seasonTable  = climateTable and climateTable[seasonName]
        local forecastStr  = "No data"
        if seasonTable and #seasonTable > 0 then
            local rndIndex = math.random(#seasonTable)
            forecastStr = seasonTable[rndIndex]
        end

        -- 2) Determine color based on keywords
        local rowColor = getEventColor(forecastStr)

        -- 3) Generate random stats (hi/lo in °C, but displayed °F)
        local stats   = getRandomWeatherStats(climateName, seasonName)
        local hiC     = stats.high
        local loC     = stats.low
        local humidity= stats.humidity
        local cRain   = stats.chanceOfRain
        local wDir    = stats.windDir
        local wSpd    = stats.windSpeed

        local hiF = (type(hiC)=="number") and cToF(hiC) or hiC
        local loF = (type(loC)=="number") and cToF(loC) or loC

        -- 4) Combine base hazards with forecast triggers
        local advisory = getAdvisory(cityName, forecastStr)

        -- 5) Insert row
        table.insert(output, "|-\n")
        table.insert(output, string.format(
[[| %s || %s || %s || %s || %s || %s || %s || %s || %s || style="background-color:%s" | %s || %s
]],
            cityName,       -- city
            climateName,    -- climate
            seasonName,     -- season
            tostring(hiF),  -- high °F
            tostring(loF),  -- low °F
            tostring(humidity),
            tostring(cRain),
            wDir,
            tostring(wSpd),
            rowColor,
            forecastStr,
            advisory
        ))
    end

    table.insert(output, "|}\n")
    return table.concat(output)
end

return p