Module:GeneralPortOperations: Difference between revisions

From MicrasWiki
Jump to navigationJump to search
NewZimiaGov (talk | contribs)
No edit summary
NewZimiaGov (talk | contribs)
No edit summary
Line 2: Line 2:
local p = {}
local p = {}


-- 1) PSSC Date
-- Returns the current PSSC year and day of year
function p.getCurrentDate()
function p.getCurrentDate()
     local startDate = os.time{year=1999, month=8, day=6}
     local startDate = os.time({year = 1999, month = 8, day = 6})
     local secondsInDay = 86400
     local secondsInDay = 86400
     local daysPerYear = 183
     local daysPerYear = 183
     local now = os.time()
     local currentDate = os.time()
     local daysElapsed = math.floor((now - startDate) / secondsInDay)
     local totalDaysElapsed = math.floor((currentDate - startDate) / secondsInDay)
     local yearFraction = daysElapsed / daysPerYear
     local yearFraction = totalDaysElapsed / daysPerYear
     local y = math.floor(yearFraction)
     local psscYear = math.floor(yearFraction)
     local d = (daysElapsed % daysPerYear) + 1
     local dayOfYear = math.floor((yearFraction - psscYear) * daysPerYear) + 1
     return y, d
     return psscYear, dayOfYear
end
end


-- Utility: pick a random element
local function randomChoice(t)
local function randomChoice(t)
     return t[math.random(#t)]
     return t[math.random(#t)]
end
end


-- Ritual cults
-- Home ports: flag (20px) + city name
local cities = {
    Vaeringheim      = "[[File:VaeringheimFlag.png|20px]] Vaeringheim",
    Somniumpolis    = "[[File:SomniumpolisFlag.png|20px]] Somniumpolis",
    Delphica        = "[[File:DelphicaFlag.png|20px]] Delphica",
    Ephyra          = "[[File:EphyraFlag.png|20px]] Ephyra",
    Norsolyra        = "[[File:NorsolyraFlag.png|20px]] Norsolyra",
    ["Skýrophos"]    = "[[File:SkyrophosFlag.png|20px]] Skýrophos",
    Riddersborg      = "[[File:RiddersborgFlag.png|20px]] Riddersborg",
    Ardclach        = "[[File:ArdclachFlag.png|20px]] Ardclach",
    Jogi            = "[[File:JogiFlag.png|20px]] Jogi",
    Sufriya          = "[[File:SufriyaFlag.png|20px]] Sufriya",
    ["Keybir-Aviv"]  = "[[File:KeybirAvivFlag.png|20px]] Keybir-Aviv",
    Aegirheim        = "[[File:AegirheimFlag.png|20px]] Aegirheim",
    Bjornopolis      = "[[File:BjornopolisFlag.png|20px]] Bjornopolis"
}
 
-- Cults for ritual vessels
local ritualCults = {
local ritualCults = {
     "Ordo Solis Invicti", "Order of Aurora Mystica", "Harmony Sanctum", "Ignis Aeternum",
     "Ordo Solis Invicti", "Order of Aurora Mystica", "Harmony Sanctum", "Ignis Aeternum",
Line 29: Line 47:
}
}


-- Military divisions
-- Divisions for military vessels
local militaryDivisions = {
local militaryDivisions = {
     "Alpazkigz Division", "Odiferia Division", "Vaeringheim Division", "Haifa Division",
     "Alpazkigz Division", "Odiferia Division", "Vaeringheim Division", "Haifa Division",
Line 35: Line 53:
}
}


-- Cargo companies by type
-- Companies for agricultural cargo
local agriCompanies = {
local agriCompanies = {
     "Gladeseed Farmers' Union", "Atterian Cattle Drivers", "Noctic Fleet",
     "Gladeseed Farmers' Union", "Atterian Cattle Drivers", "Noctic Fleet", "Jogiani Merchants of Manwine",
    "Jogiani Merchants of Manwine", "Keepers of the Grove of Zoe Elm",
    "Keepers of the Grove of Zoe Elm", "Sea-Elm Southern Meadery", "Plains of Jogi", "Ale of the Night Central Brewery",
    "Sea-Elm Southern Meadery", "Plains of Jogi", "Ale of the Night Central Brewery",
     "Camel Herders of the Jangsong Province", "Anterran Imports and Services", "Merchant Guild of the Poppy Goddess",
     "Camel Herders of the Jangsong Province", "Anterran Imports and Services",
    "Grand Cave Bee Meadery", "Cinammon Plains of Roue", "The Velvet Company", "Seamstresses of Rouge",
    "Merchant Guild of the Poppy Goddess", "Grand Cave Bee Meadery",
     "Salurian Temple of Sacred Horehound", "Bulhanu Ranchers' Association", "Suncliff Fisheries",
    "Cinammon Plains of Roue", "The Velvet Company", "Seamstresses of Rouge",
    "Ministers of Mistress Mugwort", "Blood Vineyards of the Far North", "Norsolyrian Wisp Rice Farmers Association",
     "Salurian Temple of Sacred Horehound", "Bulhanu Ranchers' Association",
     "Giid Lisea Ranching Import Company", "Bird Keepers of Saluria", "Hunters of the Giant Fanged Penguin",
    "Suncliff Fisheries", "Ministers of Mistress Mugwort",
    "Knights Castle Reindeer Herders", "Lindley Whaling Company"
    "Blood Vineyards of the Far North", "Norsolyrian Wisp Rice Farmers Association",
     "Giid Lisea Ranching Import Company", "Bird Keepers of Saluria",
    "Hunters of the Giant Fanged Penguin", "Knights Castle Reindeer Herders",
    "Lindley Whaling Company"
}
}


-- Companies for mining/manufacturing cargo
local miningCompanies = {
local miningCompanies = {
     "Baratar Corporation", "Roving Wind Farm Corporation",
     "Baratar Corporation", "Roving Wind Farm Corporation", "Thalassian Temples Granite Export Cooperative",
    "Thalassian Temples Granite Export Cooperative", "East Keltian Iron Company",
    "East Keltian Iron Company", "Mylecian Coal Ports", "Merchants of the Valley of Diamonds",
    "Mylecian Coal Ports", "Merchants of the Valley of Diamonds",
     "East Keltian Timber Company", "Onceanic Boot Company", "Commune of the Garganid Apostles",
     "East Keltian Timber Company", "Onceanic Boot Company",
    "Shï Collective", "Order of the Sphinx", "Market Hanavusu", "Somniant Stock Fund"
    "Commune of the Garganid Apostles", "Shï Collective",
    "Order of the Sphinx", "Market Hanavusu", "Somniant Stock Fund"
}
}


-- Companies for services cargo
local serviceCompanies = {
local serviceCompanies = {
     "Lake Morovia Blockade Fund", "Court of the Dark Harpy", "Hatch Ministry",
     "Lake Morovia Blockade Fund", "Court of the Dark Harpy", "Hatch Ministry",
     "Maritime Guild of the Cult of Maskmakers", "Ergonian Spy Agency",
     "Maritime Guild of the Cult of Maskmakers", "Ergonian Spy Agency", "Temple Bank of the Reformed Stripping Path",
    "Temple Bank of the Reformed Stripping Path", "Couriers of the Lizard Queen",
    "Couriers of the Lizard Queen", "Temple University of Delphica", "La Sái Ebile",
    "Temple University of Delphica", "La Sái Ebile", "Hellhound Breeders of Dragevik"
    "Hellhound Breeders of Dragevik"
}
}


local function getCompanyForCargo(cargoType)
-- Choose owner/operator based on cargo type
     if cargoType == "Agricultural" then
local function getCompanyForCargo(vesselType, cargoType)
        return randomChoice(agriCompanies)
     if vesselType == "Cargo" then
    elseif cargoType == "Mining/Manufacturing" then
        if cargoType == "Agricultural" then
        return randomChoice(miningCompanies)
            return randomChoice(agriCompanies)
    elseif cargoType == "Services" then
        elseif cargoType == "Mining/Manufacturing" then
        return randomChoice(serviceCompanies)
            return randomChoice(miningCompanies)
        elseif cargoType == "Services" then
            return randomChoice(serviceCompanies)
        end
     end
     end
     return "Independent Consortium"
     return "Independent Consortium"
end
end


-- Privateer captains
-- Privateer captain names
local captains = {
local privateerCaptains = {
     {f="Talvios", l="Karnis", n="Erebektos"},
     {first="Talvios", last="Karnis", nickname="Erebektos"},
     {f="Mirek",   l="Davros", n="Zammarion"},
     {first="Mirek", last="Davros", nickname="Zammarion"},
     {f="Ilion",   l="Quoros"},
     {first="Ilion", last="Quoros"},
     {f="Sevon",   l="Halek", n="Thamuthis"},
     {first="Sevon", last="Halek", nickname="Thamuthis"},
     {f="Caldris", l="Onir",   n="Votharion"},
     {first="Caldris", last="Onir", nickname="Votharion"},
     {f="Loras",   l="Tarnok"},
     {first="Loras", last="Tarnok"},
     {f="Vaelen", l="Koros"},
     {first="Vaelen", last="Koros"},
     {f="Daskos", l="Meyron", n="Orontion"},
     {first="Daskos", last="Meyron", nickname="Orontion"},
     {f="Kyric",   l="Fenros", n="Mekharsan"},
     {first="Kyric", last="Fenros", nickname="Mekharsan"},
     {f="Omir",   l="Thalos"},
     {first="Omir", last="Thalos"},
     {f="Baryon", l="Syrek", n="Satharkon"},
     {first="Baryon", last="Syrek", nickname="Satharkon"},
     {f="Orien",   l="Damar"},
     {first="Orien", last="Damar"},
     {f="Tharkos", l="Nyros", n="Vathmenos"},
     {first="Tharkos", last="Nyros", nickname="Vathmenos"},
     {f="Halion", l="Trevik"},
     {first="Halion", last="Trevik"},
     {f="Kelvir", l="Raan",   n="Nabarrion"},
     {first="Kelvir", last="Raan", nickname="Nabarrion"},
     {f="Lethan", l="Kohr"},
     {first="Lethan", last="Kohr"},
     {f="Zarik",   l="Tharn"},
     {first="Zarik", last="Tharn"},
     {f="Varas",   l="Jorik", n="Tharnukhet"},
     {first="Varas", last="Jorik", nickname="Tharnukhet"},
     {f="Yasrek", l="Tymon"},
     {first="Yasrek", last="Tymon"},
     {f="Aethon", l="Morvek", n="Vathromen"},
     {first="Aethon", last="Morvek", nickname="Vathromen"},
     {f="Crivos", l="Elyen"},
     {first="Crivos", last="Elyen"},
     {f="Saran",   l="Valic"},
     {first="Saran", last="Valic"},
     {f="Drevos", l="Helkan", n="Khamsuron"},
     {first="Drevos", last="Helkan", nickname="Khamsuron"},
     {f="Nyros",   l="Qalor"},
     {first="Nyros", last="Qalor"},
     {f="Talen",   l="Vorric", n="Valkhoret"}
     {first="Talen", last="Vorric", nickname="Valkhoret"}
}
}


local function getPrivateerCaptain()
-- Generate a privateer name (with ~25% chance of a nickname)
     local c = randomChoice(captains)
local function getRandomPrivateerName()
     if c.n and math.random()<0.25 then
     local cap = randomChoice(privateerCaptains)
         return string.format('Captain %s "%s" %s', c.f, c.n, c.l)
     if cap.nickname and math.random() < 0.25 then
         return string.format("Captain %s \"%s\" %s", cap.first, cap.nickname, cap.last)
    else
        return string.format("Captain %s %s", cap.first, cap.last)
     end
     end
    return string.format("Captain %s %s", c.f, c.l)
end
end


-- Home city (always Vaeringheim here)
local homeCity = "[[File:VaeringheimFlag.png|20px]] Vaeringheim"
-- 2) Build the table
function p.generateShipTable()
function p.generateShipTable()
     local vesselTypes = {"Cargo","Military","Ritual","Privateer"}
     local vesselTypes = {'Cargo', 'Military', 'Ritual', 'Privateer'}
     local cargoTypes  = {"Agricultural","Mining/Manufacturing","Services"}
     local cargoTypes  = {'Agricultural', 'Mining/Manufacturing', 'Services'}
     local errorTypes  = {
     local errorTypes  = {
         "Cargo Mislabeling","Improper Documentation",
         "Cargo Mislabeling", "Improper Documentation",
         "Surveillance Anomaly","Inspection Failure",
         "Surveillance Anomaly", "Inspection Failure",
         "Unregistered Ritual Cargo"
         "Unregistered Ritual Cargo"
     }
     }


     local y,d = p.getCurrentDate()
    -- build list of city keys
    local dateStr = string.format("Day %d, Y.%d", d, y)
     local cityKeys = {}
    local ships = {}
    for k in pairs(cities) do table.insert(cityKeys, k) end


     -- generate
     local year, day = p.getCurrentDate()
    for i=1, math.random(50,80) do
    local dateStr  = string.format("Day %d, Y.%d", day, year)
        local h,m = math.random(0,23), math.random(0,59)
        local tval = h*60 + m
        local vtype = randomChoice(vesselTypes)
        local ctype = randomChoice(cargoTypes)
        local company


         if vtype=="Ritual" then
    -- collect ships
             company = randomChoice(ritualCults)
    local ships = {}
         elseif vtype=="Military" then
    for i = 1, math.random(50,80) do
             company = randomChoice(militaryDivisions)
        local hour, min = math.random(0,23), math.random(0,59)
         elseif vtype=="Privateer" then
        local vesselType = randomChoice(vesselTypes)
             company = getPrivateerCaptain()
        local displayType = vesselType
        else
         if vesselType == "Ritual" then
            company = getCompanyForCargo(ctype)
             displayType = "Ritual - " .. randomChoice(ritualCults)
         elseif vesselType == "Military" then
             displayType = "Military - " .. randomChoice(militaryDivisions)
         elseif vesselType == "Privateer" then
             displayType = "Privateer - " .. getRandomPrivateerName()
         end
         end
        local cargo = randomChoice(cargoTypes)


         table.insert(ships, {
         ships[#ships+1] = {
             date      = dateStr,
             date      = dateStr,
             time      = string.format("%02d:%02d",h,m),
             time      = string.format("%02d:%02d", hour, min),
             sort      = tval,
             sort      = hour*60 + min,
             vessel_id  = "VM-"..math.random(10000,99999),
             vessel_id  = "VM-"..math.random(10000,99999),
             home_city  = homeCity,
             home_city  = cities[randomChoice(cityKeys)],
             type      = vtype,
             type      = displayType,
             company    = company,
             company    = getCompanyForCargo(vesselType, cargo),
             berth      = math.random(1,124),
             berth      = math.random(1,124),
             teus      = math.random(100,1000),
             teus      = math.random(100,1000),
             tonnage    = string.format("%.2f", math.random()*19000+1000),
             tonnage    = string.format("%.2f", math.random()*19000+1000),
             cargo_type = ctype,
             cargo_type = cargo,
             queue      = string.format("%.2f", math.random()*5.5+0.5),
             queue      = string.format("%.2f", math.random()*5.5+0.5),
             turnaround = string.format("%.2f", math.random()*32+4),
             turnaround = string.format("%.2f", math.random()*32+4),
             error      = (math.random()<0.2) and randomChoice(errorTypes) or "None"
             error      = (math.random()<0.2) and randomChoice(errorTypes) or "None"
         })
         }
     end
     end


     table.sort(ships, function(a,b) return a.sort<b.sort end)
     table.sort(ships, function(a,b) return a.sort < b.sort end)


     -- build wikitext
     -- build wikitext
     local out = '{| class="wikitable sortable"\n' ..
     local out = "{| class=\"wikitable sortable\"\n" ..
        '! Date !! Time !! Vessel ID !! Home City !! Type !! Owner/Operator !! Berth !! TEUs !! Tonnage !! Cargo Type !! Queue Time !! Turnaround Time !! Error'
                "! Date !! Time !! Vessel ID !! Home City !! Type !! Owner/Operator !! Berth !! TEUs !! Tonnage !! Cargo Type !! Queue (hrs) !! Turnaround (hrs) !! Error"
     for _,s in ipairs(ships) do
     for _, s in ipairs(ships) do
         out = out .. string.format(
         out = out .. string.format(
             '\n|-\n| %s || %s || %s || %s || %s || %s || %d || %d || %s || %s || %s || %s',
             "\n|-\n| %s || %s || %s || %s || %s || %s || %d || %d || %s || %s || %s || %s",
             s.date, s.time, s.vessel_id, s.home_city, s.type, s.company,
             s.date, s.time, s.vessel_id, s.home_city, s.type, s.company,
             s.berth, s.teus, s.tonnage, s.cargo_type, s.queue, s.turnaround
             s.berth, s.teus, s.tonnage, s.cargo_type, s.queue, s.turnaround
         )
         )
         if s.error~="None" then
         if s.error ~= "None" then
             out = out .. string.format(' || style="background-color:#fdd;" | %s', s.error)
             out = out .. string.format(" || style=\"background-color:#fdd;\" | %s", s.error)
         else
         else
             out = out .. ' || None'
             out = out .. " || None"
         end
         end
     end
     end


     out = out .. '\n|}\n\n' ..
     out = out .. "\n|}\n\n'''Error Key:'''\n" ..
        "'''Error Key:'''<br>" ..
          "* '''Cargo Mislabeling:''' Mismatch between manifest and actual goods\n" ..
        "* '''Cargo Mislabeling:''' Mismatch between manifest and actual goods<br>" ..
          "* '''Improper Documentation:''' Missing or outdated transit papers\n" ..
        "* '''Improper Documentation:''' Missing or outdated transit papers<br>" ..
          "* '''Surveillance Anomaly:''' Unexpected heat or movement signature\n" ..
        "* '''Surveillance Anomaly:''' Unexpected heat or movement signature<br>" ..
          "* '''Inspection Failure:''' Failed customs or hatch review\n" ..
        "* '''Inspection Failure:''' Failed customs or hatch review<br>" ..
          "* '''Unregistered Ritual Cargo:''' Religious items not pre-cleared by the Temple Bank\n"
        "* '''Unregistered Ritual Cargo:''' Religious items not pre-cleared by the Temple Bank"


     return out
     return out
Line 199: Line 213:
function p.dailyReport()
function p.dailyReport()
     local y,d = p.getCurrentDate()
     local y,d = p.getCurrentDate()
     local hdr = string.format(
     local header = string.format("'''General Port of Lake Morovia: Operational Log – Day %d, Year %d PSSC'''\n", d, y)
      "'''General Port of Lake Morovia: Operational Log – Day %d, Year %d PSSC'''<br>",
     return header .. p.generateShipTable()
      d, y
    )
     return hdr .. p.generateShipTable()
end
end


return p
return p

Revision as of 01:37, 24 April 2025

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

-- Module:GeneralPortDailyLog
local p = {}

-- Returns the current PSSC year and day of year
function p.getCurrentDate()
    local startDate = os.time({year = 1999, month = 8, day = 6})
    local secondsInDay = 86400
    local daysPerYear = 183
    local currentDate = os.time()
    local totalDaysElapsed = math.floor((currentDate - startDate) / secondsInDay)
    local yearFraction = totalDaysElapsed / daysPerYear
    local psscYear = math.floor(yearFraction)
    local dayOfYear = math.floor((yearFraction - psscYear) * daysPerYear) + 1
    return psscYear, dayOfYear
end

-- Utility: pick a random element
local function randomChoice(t)
    return t[math.random(#t)]
end

-- Home ports: flag (20px) + city name
local cities = {
    Vaeringheim      = "[[File:VaeringheimFlag.png|20px]] Vaeringheim",
    Somniumpolis     = "[[File:SomniumpolisFlag.png|20px]] Somniumpolis",
    Delphica         = "[[File:DelphicaFlag.png|20px]] Delphica",
    Ephyra           = "[[File:EphyraFlag.png|20px]] Ephyra",
    Norsolyra        = "[[File:NorsolyraFlag.png|20px]] Norsolyra",
    ["Skýrophos"]    = "[[File:SkyrophosFlag.png|20px]] Skýrophos",
    Riddersborg      = "[[File:RiddersborgFlag.png|20px]] Riddersborg",
    Ardclach         = "[[File:ArdclachFlag.png|20px]] Ardclach",
    Jogi             = "[[File:JogiFlag.png|20px]] Jogi",
    Sufriya          = "[[File:SufriyaFlag.png|20px]] Sufriya",
    ["Keybir-Aviv"]  = "[[File:KeybirAvivFlag.png|20px]] Keybir-Aviv",
    Aegirheim        = "[[File:AegirheimFlag.png|20px]] Aegirheim",
    Bjornopolis      = "[[File:BjornopolisFlag.png|20px]] Bjornopolis"
}

-- Cults for ritual vessels
local ritualCults = {
    "Ordo Solis Invicti", "Order of Aurora Mystica", "Harmony Sanctum", "Ignis Aeternum",
    "Celestial Harmony Sect", "Guild of Golden Shadows", "Azure Sentinel Sect", "Reverie Nebulous",
    "Eon Fellowship", "Order of the Umbral Oracle", "Mystery of the Verdant Embrace", "Conclave Illuminara",
    "Sanctum Vitalis", "Temple Alabaster", "Court of the Ironclad", "Accord Concordia",
    "Mystery of the Stygian Veil", "Sylvan Fellowship", "Mystery of Red Mirth", "Rex Catonis",
    "Sanctum Delphica", "Ordo Amicitia", "Temple Illuminata"
}

-- Divisions for military vessels
local militaryDivisions = {
    "Alpazkigz Division", "Odiferia Division", "Vaeringheim Division", "Haifa Division",
    "Jeseri Division", "Hatch Ministry Division", "New South Jangsong Division", "Haifan Bassaridia Division"
}

-- Companies for agricultural cargo
local agriCompanies = {
    "Gladeseed Farmers' Union", "Atterian Cattle Drivers", "Noctic Fleet", "Jogiani Merchants of Manwine",
    "Keepers of the Grove of Zoe Elm", "Sea-Elm Southern Meadery", "Plains of Jogi", "Ale of the Night Central Brewery",
    "Camel Herders of the Jangsong Province", "Anterran Imports and Services", "Merchant Guild of the Poppy Goddess",
    "Grand Cave Bee Meadery", "Cinammon Plains of Roue", "The Velvet Company", "Seamstresses of Rouge",
    "Salurian Temple of Sacred Horehound", "Bulhanu Ranchers' Association", "Suncliff Fisheries",
    "Ministers of Mistress Mugwort", "Blood Vineyards of the Far North", "Norsolyrian Wisp Rice Farmers Association",
    "Giid Lisea Ranching Import Company", "Bird Keepers of Saluria", "Hunters of the Giant Fanged Penguin",
    "Knights Castle Reindeer Herders", "Lindley Whaling Company"
}

-- Companies for mining/manufacturing cargo
local miningCompanies = {
    "Baratar Corporation", "Roving Wind Farm Corporation", "Thalassian Temples Granite Export Cooperative",
    "East Keltian Iron Company", "Mylecian Coal Ports", "Merchants of the Valley of Diamonds",
    "East Keltian Timber Company", "Onceanic Boot Company", "Commune of the Garganid Apostles",
    "Shï Collective", "Order of the Sphinx", "Market Hanavusu", "Somniant Stock Fund"
}

-- Companies for services cargo
local serviceCompanies = {
    "Lake Morovia Blockade Fund", "Court of the Dark Harpy", "Hatch Ministry",
    "Maritime Guild of the Cult of Maskmakers", "Ergonian Spy Agency", "Temple Bank of the Reformed Stripping Path",
    "Couriers of the Lizard Queen", "Temple University of Delphica", "La Sái Ebile",
    "Hellhound Breeders of Dragevik"
}

-- Choose owner/operator based on cargo type
local function getCompanyForCargo(vesselType, cargoType)
    if vesselType == "Cargo" then
        if cargoType == "Agricultural" then
            return randomChoice(agriCompanies)
        elseif cargoType == "Mining/Manufacturing" then
            return randomChoice(miningCompanies)
        elseif cargoType == "Services" then
            return randomChoice(serviceCompanies)
        end
    end
    return "Independent Consortium"
end

-- Privateer captain names
local privateerCaptains = {
    {first="Talvios", last="Karnis", nickname="Erebektos"},
    {first="Mirek", last="Davros", nickname="Zammarion"},
    {first="Ilion", last="Quoros"},
    {first="Sevon", last="Halek", nickname="Thamuthis"},
    {first="Caldris", last="Onir", nickname="Votharion"},
    {first="Loras", last="Tarnok"},
    {first="Vaelen", last="Koros"},
    {first="Daskos", last="Meyron", nickname="Orontion"},
    {first="Kyric", last="Fenros", nickname="Mekharsan"},
    {first="Omir", last="Thalos"},
    {first="Baryon", last="Syrek", nickname="Satharkon"},
    {first="Orien", last="Damar"},
    {first="Tharkos", last="Nyros", nickname="Vathmenos"},
    {first="Halion", last="Trevik"},
    {first="Kelvir", last="Raan", nickname="Nabarrion"},
    {first="Lethan", last="Kohr"},
    {first="Zarik", last="Tharn"},
    {first="Varas", last="Jorik", nickname="Tharnukhet"},
    {first="Yasrek", last="Tymon"},
    {first="Aethon", last="Morvek", nickname="Vathromen"},
    {first="Crivos", last="Elyen"},
    {first="Saran", last="Valic"},
    {first="Drevos", last="Helkan", nickname="Khamsuron"},
    {first="Nyros", last="Qalor"},
    {first="Talen", last="Vorric", nickname="Valkhoret"}
}

-- Generate a privateer name (with ~25% chance of a nickname)
local function getRandomPrivateerName()
    local cap = randomChoice(privateerCaptains)
    if cap.nickname and math.random() < 0.25 then
        return string.format("Captain %s \"%s\" %s", cap.first, cap.nickname, cap.last)
    else
        return string.format("Captain %s %s", cap.first, cap.last)
    end
end

function p.generateShipTable()
    local vesselTypes = {'Cargo', 'Military', 'Ritual', 'Privateer'}
    local cargoTypes  = {'Agricultural', 'Mining/Manufacturing', 'Services'}
    local errorTypes  = {
        "Cargo Mislabeling", "Improper Documentation",
        "Surveillance Anomaly", "Inspection Failure",
        "Unregistered Ritual Cargo"
    }

    -- build list of city keys
    local cityKeys = {}
    for k in pairs(cities) do table.insert(cityKeys, k) end

    local year, day = p.getCurrentDate()
    local dateStr  = string.format("Day %d, Y.%d", day, year)

    -- collect ships
    local ships = {}
    for i = 1, math.random(50,80) do
        local hour, min = math.random(0,23), math.random(0,59)
        local vesselType = randomChoice(vesselTypes)
        local displayType = vesselType
        if vesselType == "Ritual" then
            displayType = "Ritual - " .. randomChoice(ritualCults)
        elseif vesselType == "Military" then
            displayType = "Military - " .. randomChoice(militaryDivisions)
        elseif vesselType == "Privateer" then
            displayType = "Privateer - " .. getRandomPrivateerName()
        end
        local cargo = randomChoice(cargoTypes)

        ships[#ships+1] = {
            date       = dateStr,
            time       = string.format("%02d:%02d", hour, min),
            sort       = hour*60 + min,
            vessel_id  = "VM-"..math.random(10000,99999),
            home_city  = cities[randomChoice(cityKeys)],
            type       = displayType,
            company    = getCompanyForCargo(vesselType, cargo),
            berth      = math.random(1,124),
            teus       = math.random(100,1000),
            tonnage    = string.format("%.2f", math.random()*19000+1000),
            cargo_type = cargo,
            queue      = string.format("%.2f", math.random()*5.5+0.5),
            turnaround = string.format("%.2f", math.random()*32+4),
            error      = (math.random()<0.2) and randomChoice(errorTypes) or "None"
        }
    end

    table.sort(ships, function(a,b) return a.sort < b.sort end)

    -- build wikitext
    local out = "{| class=\"wikitable sortable\"\n" ..
                "! Date !! Time !! Vessel ID !! Home City !! Type !! Owner/Operator !! Berth !! TEUs !! Tonnage !! Cargo Type !! Queue (hrs) !! Turnaround (hrs) !! Error"
    for _, s in ipairs(ships) do
        out = out .. string.format(
            "\n|-\n| %s || %s || %s || %s || %s || %s || %d || %d || %s || %s || %s || %s",
            s.date, s.time, s.vessel_id, s.home_city, s.type, s.company,
            s.berth, s.teus, s.tonnage, s.cargo_type, s.queue, s.turnaround
        )
        if s.error ~= "None" then
            out = out .. string.format(" || style=\"background-color:#fdd;\" | %s", s.error)
        else
            out = out .. " || None"
        end
    end

    out = out .. "\n|}\n\n'''Error Key:'''\n" ..
          "* '''Cargo Mislabeling:''' Mismatch between manifest and actual goods\n" ..
          "* '''Improper Documentation:''' Missing or outdated transit papers\n" ..
          "* '''Surveillance Anomaly:''' Unexpected heat or movement signature\n" ..
          "* '''Inspection Failure:''' Failed customs or hatch review\n" ..
          "* '''Unregistered Ritual Cargo:''' Religious items not pre-cleared by the Temple Bank\n"

    return out
end

function p.dailyReport()
    local y,d = p.getCurrentDate()
    local header = string.format("'''General Port of Lake Morovia: Operational Log – Day %d, Year %d PSSC'''\n", d, y)
    return header .. p.generateShipTable()
end

return p