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 = {}


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


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


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


-- Cults for ritual vessels
-- 4) Owner/Operator pools
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",
    "Celestial Harmony Sect", "Guild of Golden Shadows", "Azure Sentinel Sect", "Reverie Nebulous",
  "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",
  "Eon Fellowship","Order of the Umbral Oracle","Mystery of the Verdant Embrace","Conclave Illuminara",
    "Sanctum Vitalis", "Temple Alabaster", "Court of the Ironclad", "Accord Concordia",
  "Sanctum Vitalis","Temple Alabaster","Court of the Ironclad","Accord Concordia",
    "Mystery of the Stygian Veil", "Sylvan Fellowship", "Mystery of Red Mirth", "Rex Catonis",
  "Mystery of the Stygian Veil","Sylvan Fellowship","Mystery of Red Mirth","Rex Catonis",
    "Sanctum Delphica", "Ordo Amicitia", "Temple Illuminata"
  "Sanctum Delphica","Ordo Amicitia","Temple Illuminata"
}
}
 
local militaryDivs = {
-- Divisions for military vessels
  "Alpazkigz Division","Odiferia Division","Vaeringheim Division","Haifa Division",
local militaryDivisions = {
  "Jeseri Division","Hatch Ministry Division","New South Jangsong Division","Haifan Bassaridia Division"
    "Alpazkigz Division", "Odiferia Division", "Vaeringheim Division", "Haifa Division",
    "Jeseri Division", "Hatch Ministry Division", "New South Jangsong Division", "Haifan Bassaridia Division"
}
}
local function randCaptain()
  local caps = {
    {f="Talvios",l="Karnis",n="Erebektos"},{f="Mirek",l="Davros",n="Zammarion"},
    {f="Ilion",l="Quoros"},{f="Sevon",l="Halek",n="Thamuthis"},{f="Caldris",l="Onir",n="Votharion"},
    {f="Loras",l="Tarnok"},{f="Vaelen",l="Koros"},{f="Daskos",l="Meyron",n="Orontion"},
    {f="Kyric",l="Fenros",n="Mekharsan"},{f="Omir",l="Thalos"},{f="Baryon",l="Syrek",n="Satharkon"},
    {f="Orien",l="Damar"},{f="Tharkos",l="Nyros",n="Vathmenos"},{f="Halion",l="Trevik"},
    {f="Kelvir",l="Raan",n="Nabarrion"},{f="Lethan",l="Kohr"},{f="Zarik",l="Tharn"},
    {f="Varas",l="Jorik",n="Tharnukhet"},{f="Yasrek",l="Tymon"},{f="Aethon",l="Morvek",n="Vathromen"},
    {f="Crivos",l="Elyen"},{f="Saran",l="Valic"},{f="Drevos",l="Helkan",n="Khamsuron"},
    {f="Nyros",l="Qalor"},{f="Talen",l="Vorric",n="Valkhoret"}
  }
  local c = randomChoice(caps)
  if c.n and math.random()<0.25 then
    return ("Captain %s \"%s\" %s"):format(c.f,c.n,c.l)
  else
    return ("Captain %s %s"):format(c.f,c.l)
  end
end


-- Cargo categories
-- 5) Cargo‐company lists
local baseCargoCats = {'Agricultural', 'Mining/Manufacturing', 'Services'}
local agriProducts = {
local extendedCats  = {'Agricultural', 'Mining/Manufacturing', 'Services', 'Unspecified'}
  "Rice","Edible Algae","Shrimp","Anterran Spicy Onion","Queen's Garlic",
 
  "Morovian Water Buffalo","Morovian Water Buffalo Beef",
-- Companies for agricultural cargo
  "Unprocessed Noctic-Rabrev Flower","Processed Noctic Rabrev Flower","Noctic-Rabrev Flower Concentrate",
local agriCompanies = {
  "Unprocessed Noctic-Rabrev Leaf","Processed Noctic-Rabrev Leaf",
    "Gladeseed Farmers' Union", "Atterian Cattle Drivers", "Noctic Fleet", "Jogiani Merchants of Manwine",
  "Unprocessed Noctic-Rabrev Leaf Concentrate","Processed Noctic-Rabrev Leaf Concentrate",
    "Keepers of the Grove of Zoe Elm", "Sea-Elm Southern Meadery", "Plains of Jogi", "Ale of the Night Central Brewery",
  "Manwine","Milkwine","Zoe Elm Resin (Unrefined)","Zoe Elm Resin (Refined)",
    "Camel Herders of the Jangsong Province", "Anterran Imports and Services", "Merchant Guild of the Poppy Goddess",
  "Sea Elm Flavored Mead","Wheat","Oats","Cereal","Hay",
    "Grand Cave Bee Meadery", "Cinammon Plains of Roue", "The Velvet Company", "Seamstresses of Rouge",
  "Ale of the Night","Camels","Camel Meat","Camel Milk","Camel Hump Water","Camel Hump Water Tea",
    "Salurian Temple of Sacred Horehound", "Bulhanu Ranchers' Association", "Suncliff Fisheries",
  "Pearls","Abalone","Opium","Hash","Mead","Cinammon",
    "Ministers of Mistress Mugwort", "Blood Vineyards of the Far North", "Norsolyrian Wisp Rice Farmers Association",
  "Velvet Worm Meat","Velvet Worm Eggs","Silk","Horehound Mead","Horehound Beer",
    "Giid Lisea Ranching Import Company", "Bird Keepers of Saluria", "Hunters of the Giant Fanged Penguin",
  "Sea Cow Beef","Atterian Armored Pufferfish","Morovian Saucer Eyed Giant Eel","Amina Crab",
    "Knights Castle Reindeer Herders", "Lindley Whaling Company"
  "Mugwort Oil","Ground Mugwort","Mugwort Tincture","Blood Infused Red Wine",
  "Wisp Rice","Giid-Lisea-Eda","Giid-Lisea-Eda Beef","Vaeringheim Turkey Meat",
  "Salurian Swamp Quail Eggs","Giant Fanged Penguin Blubber","Giant Fanged Penguin Blubber Oil Extract",
  "Coffee"
}
}
 
local mineProducts = {
-- Companies for mining/manufacturing cargo
  "Purple Granite","Iron","Steel","Concrete","Coal","Diamonds","Timber",
local miningCompanies = {
  "Mens' Boots","Womens' Boots","Garganram Sign Plains Fertilizer",
    "Baratar Corporation", "Roving Wind Farm Corporation", "Thalassian Temples Granite Export Cooperative",
  "Gold Necklaces","Gold Rings","Gold Bracelets","Gold Earrings",
    "East Keltian Iron Company", "Mylecian Coal Ports", "Merchants of the Valley of Diamonds",
  "Robes","Dresses","Tarnkappes","Coats","Perfume","Cologne","Incense","Candles"
    "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
-- 6) Choose operator and inventory
local serviceCompanies = {
local function getOperator(vt)
     "Lake Morovia Blockade Fund", "Court of the Dark Harpy", "Hatch Ministry",
     if vt=="Ritual"   then return randomChoice(ritualCults) end
     "Maritime Guild of the Cult of Maskmakers", "Ergonian Spy Agency", "Temple Bank of the Reformed Stripping Path",
    if vt=="Military" then return randomChoice(militaryDivs) end
     "Couriers of the Lizard Queen", "Temple University of Delphica", "La Sái Ebile",
    if vt=="Privateer" then return randCaptain() end
     "Hellhound Breeders of Dragevik"
    return nil
}
end
local function getOperatorOrCargoCo(vt,ct)
    local op = getOperator(vt)
     if op then return op end
     -- cargo operators were baked into company lists before; here we just show the cargo pool
     return "Independent Consortium"
end


-- Choose operator based on vessel type & cargo
local function getInventoryHtml(ct)
local function getOperator(vType, cargoType)
     if ct=="Agricultural" then
     if vType == "Ritual" then
         -- pick 3–5 random distinct products
        return randomChoice(ritualCults)
         local pick,used = {},{}
    elseif vType == "Military" then
        for _=1,math.random(3,5) do
        return randomChoice(militaryDivisions)
            local p
    elseif vType == "Privateer" then
             repeat p = randomChoice(agriProducts) until not used[p]
         -- captain generation
             used[p]=true; pick[#pick+1]=p
         local cap = randomChoice({
            {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"}
        })
        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
    elseif vType == "Cargo" then
        local html = "<ul>"
         if cargoType == "Agricultural" then
         for _,i in ipairs(pick) do html = html.."<li>"..i.."</li>" end
            return randomChoice(agriCompanies)
        return html.."</ul>"
        elseif cargoType == "Mining/Manufacturing" then
    elseif ct=="Mining/Manufacturing" then
            return randomChoice(miningCompanies)
        local pick,used = {},{}
        elseif cargoType == "Services" then
        for _=1,math.random(3,5) do
             return randomChoice(serviceCompanies)
            local p
             repeat p = randomChoice(mineProducts) until not used[p]
            used[p]=true; pick[#pick+1]=p
         end
         end
        local html = "<ul>"
        for _,i in ipairs(pick) do html = html.."<li>"..i.."</li>" end
        return html.."</ul>"
    else
        return ""
     end
     end
    return "Independent Consortium"
end
end


-- 7) Main table generation
function p.generateShipTable()
function p.generateShipTable()
     local vesselTypes = {'Cargo', 'Military', 'Ritual', 'Privateer'}
     local vesselTypes = {'Cargo','Military','Ritual','Privateer'}
     local errorTypes = {
    local cargoCats    = {'Agricultural','Mining/Manufacturing','Services'}
        "Cargo Mislabeling", "Improper Documentation",
    local allCats      = {'Agricultural','Mining/Manufacturing','Services','Unspecified'}
        "Surveillance Anomaly", "Inspection Failure",
     local errorTypes   = {
        "Unregistered Ritual Cargo"
      "Cargo Mislabeling","Improper Documentation",
      "Surveillance Anomaly","Inspection Failure","Unregistered Ritual Cargo"
     }
     }


     -- gather city keys for random assignment
     -- collect city keys
     local cityKeys = {}
     local cityKeys = {}
     for k in pairs(cities) do table.insert(cityKeys, k) end
     for k in pairs(cities) do cityKeys[#cityKeys+1]=k end


     local year, day = p.getCurrentDate()
    -- seed & date
     local dateStr = string.format("Day %d, Y.%d", day, year)
     local y,d = p.getCurrentDate()
     local dateStr = ("Day %d, Y.%d"):format(d,y)


     -- build ship entries
     -- build ships
     local ships = {}
     local ships = {}
     for i = 1, math.random(50, 80) do
     for i=1,math.random(50,80) do
         local h, m   = math.random(0,23), math.random(0,59)
         local h,m = math.random(0,23), math.random(0,59)
         local vType  = randomChoice(vesselTypes)
         local vt  = randomChoice(vesselTypes)
         local cargo  = (vType=="Cargo")
         local ct  = (vt=="Cargo") and randomChoice(cargoCats) or randomChoice(allCats)
                      and randomChoice(baseCargoCats)
                      or randomChoice(extendedCats)
         ships[#ships+1] = {
         ships[#ships+1] = {
             date       = dateStr,
             date = dateStr,
             time       = string.format("%02d:%02d", h, m),
             time = ("%02d:%02d"):format(h,m),
             sort       = h*60 + m,
             sort = h*60 + m,
             vessel_id  = "VM-"..math.random(10000,99999),
             id  = "VM-"..math.random(10000,99999),
             home_city  = cities[randomChoice(cityKeys)],
             home = cities[randomChoice(cityKeys)],
             type       = vType,
             type = vt,
             operator   = getOperator(vType, cargo),
             op   = getOperatorOrCargoCo(vt,ct),
             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 = ("%.2f"):format(math.random()*19000+1000),
             cargo_type = cargo,
             cat  = ct,
             queue     = string.format("%.2f", math.random()*5.5+0.5),
            inv  = getInventoryHtml(ct),
             turnaround = string.format("%.2f", math.random()*32+4),
             queue     = ("%.2f"):format(math.random()*5.5+0.5),
             error      = (math.random()<0.2) and randomChoice(errorTypes) or "None"
             turnaround= ("%.2f"):format(math.random()*32+4),
             err = (math.random()<0.2) and randomChoice(errorTypes) or "None"
         }
         }
     end
     end
Line 180: Line 180:
     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 table
     -- assemble 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 (hrs) !! Turnaround (hrs) !! 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(
        -- cargo cell with embedded inventory
            "\n|-\n| %s || %s || %s || %s || %s || %s || %d || %d || %s || %s || %s || %s",
        local cargoCell = s.cat .. s.inv
            s.date, s.time, s.vessel_id, s.home_city, s.type, s.operator,
         out = out .. ("\n|- \n| %s || %s || %s || %s || %s || %s || %d || %d || %s || %s || %s || %s")
            s.berth, s.teus, s.tonnage, s.cargo_type, s.queue, s.turnaround
          :format(s.date, s.time, s.id, s.home, s.type, s.op,
        )
                  s.berth, s.teus, s.tonnage, cargoCell, s.queue, s.turnaround)
         if s.error ~= "None" then
         if s.err ~= "None" then
             out = out .. string.format(" || style=\"background-color:#fdd;\" | %s", s.error)
             out = out .. (" || style=\"background-color:#fdd;\" | %s"):format(s.err)
         else
         else
             out = out .. " || None"
             out = out .. " || None"
         end
         end
     end
     end
     out = out .. "\n|}\n\n'''Error Key:'''\n" ..
     out = out .. "\n|}\n\n'''Error Key:'''\n" ..
          "* '''Cargo Mislabeling:''' Mismatch between manifest and actual goods\n" ..
        "* '''Cargo Mislabeling:''' Mismatch between manifest and actual goods\n" ..
          "* '''Improper Documentation:''' Missing or outdated transit papers\n" ..
        "* '''Improper Documentation:''' Missing or outdated transit papers\n" ..
          "* '''Surveillance Anomaly:''' Unexpected heat or movement signature\n" ..
        "* '''Surveillance Anomaly:''' Unexpected heat or movement signature\n" ..
          "* '''Inspection Failure:''' Failed customs or hatch review\n" ..
        "* '''Inspection Failure:''' Failed customs or hatch review\n" ..
          "* '''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\n"
 
     return out
     return out
end
end
Line 208: Line 206:
function p.dailyReport()
function p.dailyReport()
     local y,d = p.getCurrentDate()
     local y,d = p.getCurrentDate()
     local header = string.format("'''General Port of Lake Morovia: Operational Log – Day %d, Year %d PSSC'''\n", d, y)
     local hdr = ("'''General Port of Lake Morovia: Operational Log – Day %d, Year %d PSSC'''\n"):format(d,y)
     return header .. p.generateShipTable()
     return hdr .. p.generateShipTable()
end
end


return p
return p

Revision as of 01:56, 24 April 2025

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

-- Module:GeneralPortDailyLog
local p = {}

-- 1) Current PSSC date
function p.getCurrentDate()
    local start = os.time{year=1999,month=8,day=6}
    local now   = os.time()
    local secPerDay, daysPerYear = 86400, 183
    local elapsed = math.floor((now - start) / secPerDay)
    local yearFrac = elapsed / daysPerYear
    local y = math.floor(yearFrac)
    local d = math.floor((yearFrac - y) * daysPerYear) + 1
    return y, d
end

-- 2) Random helper
local function randomChoice(t)
    return t[math.random(#t)]
end

-- 3) Home‐port cities & flags
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",
    Skyrophos       = "[[File:SkyrophosFlag.png|20px]] Skyrophos",
    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"
}

-- 4) Owner/Operator pools
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"
}
local militaryDivs = {
  "Alpazkigz Division","Odiferia Division","Vaeringheim Division","Haifa Division",
  "Jeseri Division","Hatch Ministry Division","New South Jangsong Division","Haifan Bassaridia Division"
}
local function randCaptain()
  local caps = {
    {f="Talvios",l="Karnis",n="Erebektos"},{f="Mirek",l="Davros",n="Zammarion"},
    {f="Ilion",l="Quoros"},{f="Sevon",l="Halek",n="Thamuthis"},{f="Caldris",l="Onir",n="Votharion"},
    {f="Loras",l="Tarnok"},{f="Vaelen",l="Koros"},{f="Daskos",l="Meyron",n="Orontion"},
    {f="Kyric",l="Fenros",n="Mekharsan"},{f="Omir",l="Thalos"},{f="Baryon",l="Syrek",n="Satharkon"},
    {f="Orien",l="Damar"},{f="Tharkos",l="Nyros",n="Vathmenos"},{f="Halion",l="Trevik"},
    {f="Kelvir",l="Raan",n="Nabarrion"},{f="Lethan",l="Kohr"},{f="Zarik",l="Tharn"},
    {f="Varas",l="Jorik",n="Tharnukhet"},{f="Yasrek",l="Tymon"},{f="Aethon",l="Morvek",n="Vathromen"},
    {f="Crivos",l="Elyen"},{f="Saran",l="Valic"},{f="Drevos",l="Helkan",n="Khamsuron"},
    {f="Nyros",l="Qalor"},{f="Talen",l="Vorric",n="Valkhoret"}
  }
  local c = randomChoice(caps)
  if c.n and math.random()<0.25 then
    return ("Captain %s \"%s\" %s"):format(c.f,c.n,c.l)
  else
    return ("Captain %s %s"):format(c.f,c.l)
  end
end

-- 5) Cargo‐company lists
local agriProducts = {
  "Rice","Edible Algae","Shrimp","Anterran Spicy Onion","Queen's Garlic",
  "Morovian Water Buffalo","Morovian Water Buffalo Beef",
  "Unprocessed Noctic-Rabrev Flower","Processed Noctic Rabrev Flower","Noctic-Rabrev Flower Concentrate",
  "Unprocessed Noctic-Rabrev Leaf","Processed Noctic-Rabrev Leaf",
  "Unprocessed Noctic-Rabrev Leaf Concentrate","Processed Noctic-Rabrev Leaf Concentrate",
  "Manwine","Milkwine","Zoe Elm Resin (Unrefined)","Zoe Elm Resin (Refined)",
  "Sea Elm Flavored Mead","Wheat","Oats","Cereal","Hay",
  "Ale of the Night","Camels","Camel Meat","Camel Milk","Camel Hump Water","Camel Hump Water Tea",
  "Pearls","Abalone","Opium","Hash","Mead","Cinammon",
  "Velvet Worm Meat","Velvet Worm Eggs","Silk","Horehound Mead","Horehound Beer",
  "Sea Cow Beef","Atterian Armored Pufferfish","Morovian Saucer Eyed Giant Eel","Amina Crab",
  "Mugwort Oil","Ground Mugwort","Mugwort Tincture","Blood Infused Red Wine",
  "Wisp Rice","Giid-Lisea-Eda","Giid-Lisea-Eda Beef","Vaeringheim Turkey Meat",
  "Salurian Swamp Quail Eggs","Giant Fanged Penguin Blubber","Giant Fanged Penguin Blubber Oil Extract",
  "Coffee"
}
local mineProducts = {
  "Purple Granite","Iron","Steel","Concrete","Coal","Diamonds","Timber",
  "Mens' Boots","Womens' Boots","Garganram Sign Plains Fertilizer",
  "Gold Necklaces","Gold Rings","Gold Bracelets","Gold Earrings",
  "Robes","Dresses","Tarnkappes","Coats","Perfume","Cologne","Incense","Candles"
}

-- 6) Choose operator and inventory
local function getOperator(vt)
    if vt=="Ritual"    then return randomChoice(ritualCults) end
    if vt=="Military"  then return randomChoice(militaryDivs) end
    if vt=="Privateer" then return randCaptain() end
    return nil
end
local function getOperatorOrCargoCo(vt,ct)
    local op = getOperator(vt)
    if op then return op end
    -- cargo operators were baked into company lists before; here we just show the cargo pool
    return "Independent Consortium"
end

local function getInventoryHtml(ct)
    if ct=="Agricultural" then
        -- pick 3–5 random distinct products
        local pick,used = {},{}
        for _=1,math.random(3,5) do
            local p
            repeat p = randomChoice(agriProducts) until not used[p]
            used[p]=true; pick[#pick+1]=p
        end
        local html = "<ul>"
        for _,i in ipairs(pick) do html = html.."<li>"..i.."</li>" end
        return html.."</ul>"
    elseif ct=="Mining/Manufacturing" then
        local pick,used = {},{}
        for _=1,math.random(3,5) do
            local p
            repeat p = randomChoice(mineProducts) until not used[p]
            used[p]=true; pick[#pick+1]=p
        end
        local html = "<ul>"
        for _,i in ipairs(pick) do html = html.."<li>"..i.."</li>" end
        return html.."</ul>"
    else
        return ""
    end
end

-- 7) Main table generation
function p.generateShipTable()
    local vesselTypes = {'Cargo','Military','Ritual','Privateer'}
    local cargoCats    = {'Agricultural','Mining/Manufacturing','Services'}
    local allCats      = {'Agricultural','Mining/Manufacturing','Services','Unspecified'}
    local errorTypes   = {
      "Cargo Mislabeling","Improper Documentation",
      "Surveillance Anomaly","Inspection Failure","Unregistered Ritual Cargo"
    }

    -- collect city keys
    local cityKeys = {}
    for k in pairs(cities) do cityKeys[#cityKeys+1]=k end

    -- seed & date
    local y,d = p.getCurrentDate()
    local dateStr = ("Day %d, Y.%d"):format(d,y)

    -- build ships
    local ships = {}
    for i=1,math.random(50,80) do
        local h,m = math.random(0,23), math.random(0,59)
        local vt  = randomChoice(vesselTypes)
        local ct  = (vt=="Cargo") and randomChoice(cargoCats) or randomChoice(allCats)
        ships[#ships+1] = {
            date = dateStr,
            time = ("%02d:%02d"):format(h,m),
            sort = h*60 + m,
            id   = "VM-"..math.random(10000,99999),
            home = cities[randomChoice(cityKeys)],
            type = vt,
            op   = getOperatorOrCargoCo(vt,ct),
            berth= math.random(1,124),
            teus = math.random(100,1000),
            tonnage = ("%.2f"):format(math.random()*19000+1000),
            cat  = ct,
            inv  = getInventoryHtml(ct),
            queue     = ("%.2f"):format(math.random()*5.5+0.5),
            turnaround= ("%.2f"):format(math.random()*32+4),
            err = (math.random()<0.2) and randomChoice(errorTypes) or "None"
        }
    end

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

    -- assemble 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
        -- cargo cell with embedded inventory
        local cargoCell = s.cat .. s.inv
        out = out .. ("\n|- \n| %s || %s || %s || %s || %s || %s || %d || %d || %s || %s || %s || %s")
          :format(s.date, s.time, s.id, s.home, s.type, s.op,
                  s.berth, s.teus, s.tonnage, cargoCell, s.queue, s.turnaround)
        if s.err ~= "None" then
            out = out .. (" || style=\"background-color:#fdd;\" | %s"):format(s.err)
        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 hdr = ("'''General Port of Lake Morovia: Operational Log – Day %d, Year %d PSSC'''\n"):format(d,y)
    return hdr .. p.generateShipTable()
end

return p