Module:AutoUpdateServPrices

From MicrasWiki
Revision as of 00:10, 16 February 2026 by NewZimiaGov (talk | contribs)
Jump to navigationJump to search

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

---------------------------------------------------------
-- Module:AutoUpdateServPrices (OPTIMIZED)
--
-- Fix for Scribunto timeout:
--  • Caches city-level signals once per unique HQ city:
--      - Forecast opsData
--      - Hatch daily report city counts (one report per day; counts cached)
--      - War League table city counts (one table per day; counts cached)
--      - Outbreak severity (one call per city; cached)
--  • Avoids repeated string concatenation in loops (uses table buffers).
--  • Keeps same output format and pricing logic as the previous rewrite.
---------------------------------------------------------
local p = {}

---------------------------------------------------------
-- getCurrentDate
---------------------------------------------------------
local function 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

	local month, dayOfMonth
	if dayOfYear <= 61 then
		month = 1
		dayOfMonth = dayOfYear
	elseif dayOfYear <= 122 then
		month = 2
		dayOfMonth = dayOfYear - 61
	else
		month = 3
		dayOfMonth = dayOfYear - 122
	end

	return string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear), dayOfMonth, month, psscYear, dayOfYear
end

---------------------------------------------------------
-- Product data (FULL LIST — from oldid=380847)
---------------------------------------------------------
local products = {
	{"Draped Flag Linens (Foreign Vessels)", "Lake Morovia Blockade Fund - Hatch Ministry", 1.40, "sheets"},
	{"Dismantled Minting Equipment", "Lake Morovia Blockade Fund - Hatch Ministry", .7, "assemblies"},
	{"Decertified Seal Stamps (Foreign Commissions)", "Lake Morovia Blockade Fund - Hatch Ministry", 1.9, "sets"},
	{"Declassified Naval Cargo Covers", "Lake Morovia Blockade Fund - Hatch Ministry", 6.0, "tarps"},
	{"Confiscated Calibration Weights", "Lake Morovia Blockade Fund - Hatch Ministry", 8.8, "sets"},
	{"Crated Trade Uniforms (Non-Domestic Origin)", "Lake Morovia Blockade Fund - Hatch Ministry", 1.30, "articles"},
	{"Defaced Customs Plaques", "Lake Morovia Blockade Fund - Hatch Ministry", 1.7, "plaques"},
	{"Baled Promotional Ephemera", "Lake Morovia Blockade Fund - Hatch Ministry", 4.80, "kg"},
	{"Foreign Coinage (Struck Before Blockade)", "Lake Morovia Blockade Fund - Hatch Ministry", 3.1, "coins"},
	{"Embroidered Foreign Diplomatic Standards", "Lake Morovia Blockade Fund - Hatch Ministry", 4, "banners"},
	{"Blocked Port Registry Books", "Lake Morovia Blockade Fund - Hatch Ministry", 1.2, "ledgers"},
	{"Disassembled Broadcast Relays", "Lake Morovia Blockade Fund - Hatch Ministry", 6, "units"},
	{"Stamps (Confiscated)", "Lake Morovia Blockade Fund - Hatch Ministry", 7.0, "sheets"},

	{"Confiscated Trade Crates", "Hatch Ministry", 1.1, "units"},
	{"Mixed Merchant Cargo", "Hatch Ministry", 5.2, "tons"},
	{"Captured Textiles (Raw & Finished)", "Hatch Ministry", 3.40, "bolts"},
	{"Illicit Grain Stores", "Hatch Ministry", 3.6, "tons"},
	{"Contraband Alcohol", "Hatch Ministry", 1.1, "bottles"},
	{"Seized Foreign Coinage", "Hatch Ministry", 10, "coins"},
	{"Recovered Cargo Manifests", "Hatch Ministry", 3.33, "scrolls"},
	{"Bulk Dyes and Spices (Unmarked Origin)", "Hatch Ministry", 7.220, "kg"},
	{"Captured Livestock (Deck Transport)", "Hatch Ministry", 2.6, "head"},
	{"Foreign Trade Seals and Emblems", "Hatch Ministry", 1.22, "sets"},
	{"Unregistered Luxury Cargo", "Hatch Ministry", 1.4, "tons"},
	{"Recovered Safe Boxes", "Hatch Ministry", .7, "chests"},
	{"Stamped Silver Bars", "Hatch Ministry", 3.90, "kg"},
	{"Captured Naval Uniforms and Insignia", "Hatch Ministry", 5.5, "sets"},
	{"Lost Port Authority Documents", "Hatch Ministry", 1.4, "scrolls"},
	{"High-Value Personal Effects", "Hatch Ministry", 6.8, "items"},
	{"Private Letters and Ship Logs", "Hatch Ministry", 4.1, "volumes"},

	{ "Faces", "Maritime Guild of the Cult of Maskmakers", 0.03, "masks" },
	{ "Festival Faces (painted set)", "Maritime Guild of the Cult of Maskmakers", 0.06, "sets" },
	{ "Plain Mask Blanks (carving-grade)", "Maritime Guild of the Cult of Maskmakers", 0.04, "masks" },
	{ "Ceremonial Masks (lacquered)", "Maritime Guild of the Cult of Maskmakers", 0.08, "masks" },
	{ "Dockworker Faceplates (saltproof)", "Maritime Guild of the Cult of Maskmakers", 0.05, "masks" },
	{ "Theatrical Half-Masks (performance)", "Maritime Guild of the Cult of Maskmakers", 0.04, "masks" },
	{ "Mask Straps & Fasteners (bundled)", "Maritime Guild of the Cult of Maskmakers", 0.02, "bundles" },
	{ "Mask Repair & Refinish Service", "Maritime Guild of the Cult of Maskmakers", 0.03, "repairs" },
	{ "Identity Veil Charms (token)", "Maritime Guild of the Cult of Maskmakers", 0.05, "tokens" },
	{ "Crated Mask Lots (mixed export)", "Maritime Guild of the Cult of Maskmakers", 0.12, "crates" },

	{ "Spies", "Ergonian Spy Agency", 0.01, "assignments" },
	{ "Surveillance Package (basic tail)", "Ergonian Spy Agency", 0.04, "assignments" },
	{ "Counterintelligence Sweep (port office)", "Ergonian Spy Agency", 0.09, "operations" },
	{ "Background Dossier (merchant vetting)", "Ergonian Spy Agency", 0.06, "reports" },
	{ "Cipher & Codebook Service (per batch)", "Ergonian Spy Agency", 0.03, "batches" },
	{ "Dead-Drop Setup (secure route)", "Ergonian Spy Agency", 0.05, "routes" },
	{ "Infiltration Placement (short term)", "Ergonian Spy Agency", 0.12, "placements" },
	{ "Rumor Injection (market shaping)", "Ergonian Spy Agency", 0.07, "campaigns" },
	{ "Signal Intercept Review (limited)", "Ergonian Spy Agency", 0.08, "reviews" },
	{ "Safehouse Lease (weekly)", "Ergonian Spy Agency", 0.10, "weeks" },

	{"Missionaries of the Order Aurora Mystica", "Temple Bank of the Reformed Stripping Path", 0.05, "teams"},
	{"Missionaries of Harmony Sanctum", "Temple Bank of the Reformed Stripping Path", 0.09, "teams"},
	{"Missionaries of Ignis Aeternum", "Temple Bank of the Reformed Stripping Path", 0.09, "teams"},
	{"Missionaries of Celestial Harmony Sect", "Temple Bank of the Reformed Stripping Path", 0.08, "teams"},
	{"Missionaries of the Guild of Golden Shadows", "Temple Bank of the Reformed Stripping Path", 0.05, "teams"},
	{"Missionaries of the Azure Sentinel Sect", "Temple Bank of the Reformed Stripping Path", 0.01, "teams"},
	{"Missionaries of Reverie Nebulous", "Temple Bank of the Reformed Stripping Path", 0.10, "teams"},
	{"Missionaries of the Eon Fellowship", "Temple Bank of the Reformed Stripping Path", 0.09, "teams"},
	{"Missionaries of the Order of the Umbral Oracle", "Temple Bank of the Reformed Stripping Path", 0.07, "teams"},
	{"Missionaries of the Mystery of the Verdant Embrace", "Temple Bank of the Reformed Stripping Path", 0.10, "teams"},
	{"Missionaries of Conclace Illuminara", "Temple Bank of the Reformed Stripping Path", 0.02, "teams"},
	{"Missionaries of Sanctum Vitalis", "Temple Bank of the Reformed Stripping Path", 0.06, "teams"},
	{"Missionaries of Temple Alabaster", "Temple Bank of the Reformed Stripping Path", 0.09, "teams"},
	{"Missionaries of the Court of the Ironclad", "Temple Bank of the Reformed Stripping Path", 0.06, "teams"},
	{"Missionaries of Concord Accordia", "Temple Bank of the Reformed Stripping Path", 0.02, "teams"},
	{"Missionaries of the Mystery of the Stygian Veil", "Temple Bank of the Reformed Stripping Path", 0.03, "teams"},
	{"Missionaries of the Sylvan Fellowship", "Temple Bank of the Reformed Stripping Path", 0.09, "teams"},
	{"Missionaries of the Mystery of Red Mirth", "Temple Bank of the Reformed Stripping Path", 0.06, "teams"},
	{"Missionaries of Rex Catonis", "Temple Bank of the Reformed Stripping Path", 0.07, "teams"},
	{"Missionaries of Sanctum Delphica", "Temple Bank of the Reformed Stripping Path", 0.09, "teams"},
	{"Missionaries of Ordo Amictia", "Temple Bank of the Reformed Stripping Path", 0.06, "teams"},
	{"Missionaries of Temple Illuminata", "Temple Bank of the Reformed Stripping Path", 0.05, "teams"},

	{ "Couriers", "Couriers of the Lizard Queen", 0.04, "dispatches" },
	{ "Wisp Ward Talismans", "Couriers of the Lizard Queen", 0.10, "amulets" },
	{ "Night-Run Dispatch (priority)", "Couriers of the Lizard Queen", 0.08, "dispatches" },
	{ "Canal Skiff Courier Trip", "Couriers of the Lizard Queen", 0.06, "trips" },
	{ "Caravan Relay Courier (long route)", "Couriers of the Lizard Queen", 0.12, "dispatches" },
	{ "Sealed Packet Service (tamperproof)", "Couriers of the Lizard Queen", 0.09, "packets" },
	{ "Ciphered Message Prep (batch)", "Couriers of the Lizard Queen", 0.05, "batches" },
	{ "Ward Chalk (threshold marking)", "Couriers of the Lizard Queen", 0.04, "packs" },
	{ "Ward Incense Sticks (protective)", "Couriers of the Lizard Queen", 0.06, "sticks" },
	{ "Emergency Beacon Token (messenger call)", "Couriers of the Lizard Queen", 0.14, "tokens" },
	{"Wisp Ward Talismans", "Couriers of the Lizard Queen", 0.10, "amulets"},

	{ "Credit Hours", "Temple University of Delphica", 3.00, "credits" },
	{ "Tutorial Sessions (small group)", "Temple University of Delphica", 0.60, "sessions" },
	{ "Lab Access Pass (day)", "Temple University of Delphica", 0.35, "passes" },
	{ "Library Archive Access (restricted)", "Temple University of Delphica", 0.55, "passes" },
	{ "Exam Proctoring (certified)", "Temple University of Delphica", 0.40, "exams" },
	{ "Trade Certification (clerks & tally)", "Temple University of Delphica", 0.95, "certificates" },
	{ "Language Translation (academic)", "Temple University of Delphica", 0.12, "pages" },
	{ "Lecture Hall Rental (per hour)", "Temple University of Delphica", 0.45, "hours" },
	{ "Field Study Course Seat (port logistics)", "Temple University of Delphica", 1.20, "seats" },
	{ "Research Abstract Review (submission)", "Temple University of Delphica", 0.25, "submissions" },

	{ "Circuses", "La Sái Ebile", 0.24, "venues" },
	{ "Performances", "La Sái Ebile", 0.11, "acts" },
	{ "Acrobat Troupe Booking", "La Sái Ebile", 0.16, "troupes" },
	{ "Musician Set (evening)", "La Sái Ebile", 0.14, "sets" },
	{ "Masked Parade Package", "La Sái Ebile", 0.20, "parades" },
	{ "Ticket Blocks (printed)", "La Sái Ebile", 0.09, "tickets" },
	{ "Stage Rental (per day)", "La Sái Ebile", 0.18, "days" },
	{ "Lighting & Rigging Kit", "La Sái Ebile", 0.15, "kits" },
	{ "Costume Hire (bundle)", "La Sái Ebile", 0.10, "bundles" },
	{ "Show Permits & Routing (festival)", "La Sái Ebile", 0.13, "permits" },

	{"Passenger Rail Tickets", "Trans-Morovian Express", 1.2, "tickets"},
	{"Luxury Cabin Reservations", "Trans-Morovian Express", 4.5, "cabins"},
	{"Freight Car Leasing Contracts", "Trans-Morovian Express", .60, "agreements"},
	{"Overland Courier Deliveries", "Trans-Morovian Express", .23, "parcels"},
	{"Secure Cargo Vaults", "Trans-Morovian Express", .39, "units"},
	{"Customs Bypass Licenses", "Trans-Morovian Express", .71, "permits"},
	{"Railway Advertising Rights", "Trans-Morovian Express", .18, "slots"},
	{"Timetable Access Codes", "Trans-Morovian Express", .5, "keys"},
	{"Locomotive Repair Services", "Trans-Morovian Express", .57, "contracts"},
	{"Historical Route Tours", "Trans-Morovian Express", .20, "tours"},
	{"Private Charter Lines", "Trans-Morovian Express", .84, "routes"},
	{"Coal Tender Refills", "Trans-Morovian Express", .33, "loads"},

	{"Hellhound (scout)", "Hellhound Breeders of Dragevik", 0.03, "hounds"},
	{"Hellhound (soldier)", "Hellhound Breeders of Dragevik", 0.05, "hounds"},
	{"Hellhound (spy)", "Hellhound Breeders of Dragevik", 0.15, "hounds"},

	{"Priestesses of the Pharmacon Sect (Anti-Parasitic Medicine)", "Pharmacon Sect", 0.07, "doses"},
	{"Priestesses of the Pharmacon Sect (Antifungal/Respiratory Medicine)", "Pharmacon Sect", 0.08, "doses"},
	{"Priestesses of the Pharmacon Sect (Trauma/Battle Medicine)", "Pharmacon Sect", 0.09, "doses"},
	{"Priestesses of the Pharmacon Sect (Memory and Mind Treatment)", "Pharmacon Sect", 0.06, "doses"},
	{"Priestesses of the Pharmacon Sect (Immune Boost Medicine)", "Pharmacon Sect", 0.05, "doses"},
	{"Priestesses of the Pharmacon Sect (Respiratory Clearing Medicine)", "Pharmacon Sect", 0.05, "doses"},
	{"Priestesses of the Pharmacon Sect (Fertility and Childbirth Medicine)", "Pharmacon Sect", 0.04, "doses"},
	{"Priestesses of the Pharmacon Sect (Ritual Purification Incense)", "Pharmacon Sect", 0.03, "sticks"},
	{"Priestesses of the Pharmacon Sect (Medicinal Alcohol)", "Pharmacon Sect", 0.02, "bottles"},
	{"Priestesses of the Pharmacon Sect (Detoxification Medicine)", "Pharmacon Sect", 0.05, "doses"},

	{ "Security Contractors", "Skyrophian Security Contractors*", 0.03, "Assignments" },
	{ "Local Guard Detail (basic)", "Skyrophian Security Contractors*", 0.08, "assignments" },
	{ "Cargo Escort (short haul)", "Skyrophian Security Contractors*", 0.11, "escorts" },
	{ "Gatehouse Rotation (weekly)", "Skyrophian Security Contractors*", 0.06, "weeks" },
	{ "Night Watch (dock perimeter)", "Skyrophian Security Contractors*", 0.10, "shifts" },
	{ "Risk Assessment Report (site)", "Skyrophian Security Contractors*", 0.09, "reports" },
	{ "Incident Response Dispatch (rapid)", "Skyrophian Security Contractors*", 0.20, "responses" },
	{ "Maritime Watch Rotation (dockside)", "Skyrophian Security Contractors*", 0.14, "rotations" },
	{ "Security Training Session (staff)", "Skyrophian Security Contractors*", 0.08, "sessions" },
	{ "Access Badge Screening (batch)", "Skyrophian Security Contractors*", 0.06, "batches" },

	{ "Postal Workers", "Haifadora Postal Service*", 0.10, "Assignments" },
	{ "Standard Letter Delivery (bundle)", "Haifadora Postal Service*", 0.06, "bundles" },
	{ "Parcel Shipment (domestic)", "Haifadora Postal Service*", 0.12, "parcels" },
	{ "Express Courier Dispatch (same-day)", "Haifadora Postal Service*", 0.18, "dispatches" },
	{ "Registered Mail Filing", "Haifadora Postal Service*", 0.09, "filings" },
	{ "P.O. Box Rental (monthly)", "Haifadora Postal Service*", 0.22, "months" },
	{ "Stamp Sheets (standard)", "Haifadora Postal Service*", 0.08, "sheets" },
	{ "Sorting & Bagging Service (bulk)", "Haifadora Postal Service*", 0.11, "services" },
	{ "Cross-Straits Mail Sack (sealed)", "Haifadora Postal Service*", 0.20, "sacks" },
	{ "Customs Mail Forms (certified)", "Haifadora Postal Service*", 0.05, "forms" },

	{"Recovered Treasure Chests", "Fleet of Rouge Divers", 6, "units"},
	{"Antique Pottery", "Fleet of Rouge Divers", 40, "pieces"},
	{"Salvaged Artifacts", "Fleet of Rouge Divers", 55, "items"},
	{"Driftwood Timber", "Fleet of Rouge Divers", 3.2, "tons"},
	{"Recovered Jewelry", "Fleet of Rouge Divers", 12, "sets"},
	{"Glassware (Recovered)", "Fleet of Rouge Divers", 90, "pieces"},
	{"Metal Ingots (Mixed)", "Fleet of Rouge Divers", 70, "kg"},

	{"Butterscotch Merchants", "Merchant Caravans of the Candy Kingdom", .36, "Caravans"},
	{"Candy Exports", "Merchant Caravans of the Candy Kingdom", .23, "tons"},
	{"Sugar Blocks", "Merchant Caravans of the Candy Kingdom", .44, "blocks"},
	{"Rare Spices", "Merchant Caravans of the Candy Kingdom", .15, "crates"},
	{"Milk Caramels", "Merchant Caravans of the Candy Kingdom", .51, "packs"},
	{"Marzipan Candy", "Merchant Caravans of the Candy Kingdom", .49, "packs"},
	{"Honey-Glazed Almonds", "Merchant Caravans of the Candy Kingdom", .40, "bags"},
	{"Seasonal Festival Candies", "Merchant Caravans of the Candy Kingdom", .33, "bundles"},
	{"Caravan Route Access Fees", "Merchant Caravans of the Candy Kingdom", .24, "permits"},
	{"Contracted Caravan Guards", "Merchant Caravans of the Candy Kingdom", .28, "escorts"},

	{"Broadcast Sponsorship Slots", "Bassaridian Broadcasting Corporation", .55, "slots"},
	{"Morning Program Advertisements", "Bassaridian Broadcasting Corporation", .39, "ads"},
	{"Emergency Alert Announcements", "Bassaridian Broadcasting Corporation", .22, "alerts"},
	{"Live Cultural Event Coverage", "Bassaridian Broadcasting Corporation", .68, "events"},
	{"Religious Broadcast Packages", "Bassaridian Broadcasting Corporation", .44, "packages"},
	{"Rural Signal Relay Contracts", "Bassaridian Broadcasting Corporation", .31, "contracts"},
	{"Public Service Bulletins", "Bassaridian Broadcasting Corporation", .12, "bulletins"},
	{"Interview and Feature Packages", "Bassaridian Broadcasting Corporation", .18, "segments"},
	{"Radio Licensing and Syndication", "Bassaridian Broadcasting Corporation", .27, "licenses"},
	{"Transmission Maintenance (tower)", "Bassaridian Broadcasting Corporation", .20, "services"},

	{"Priestesses of the Ledger (Employee Loyalty Audits)", "Temple of Aprobelle", 2.7, "reports"},
	{"Watchful Priestesses (Real-Time Behavior Monitoring)", "Temple of Aprobelle", 9.5, "profiles"},
	{"Priestesses of Discourse (Disloyalty Flagging Alerts)", "Temple of Aprobelle", 8.1, "alerts"},
	{"Priestesses of the Veil (Insider Threat Screening)", "Temple of Aprobelle", 2.1, "cycles"},
	{"Priestesses of the Pulse (Routine Polygraph Sessions)", "Temple of Aprobelle", 2.3, "sessions"},
	{"Priestesses of the Mirror (Population Mood Tracking)", "Temple of Aprobelle", 6.8, "surveys"},
	{"Silencing Priestesses (Rumor Suppression Bulletins)", "Temple of Aprobelle", 3.5, "issues"},
	{"Resolute Priestesses (Anomaly Response Team Dispatches)", "Temple of Aprobelle", 0.14, "responses"},
	{"Priestesses of Encouragement (Whistleblower Reward Packages)", "Temple of Aprobelle", 0.55, "bonuses"},

	{"Camel Train Transport (Local Cargo)", "Keltian Steppe Caravan Company", 1.15, "tons"},
	{"Alperkin Couriers (Highland Legs)", "Keltian Steppe Caravan Company", 0.18, "dispatches"},
	{"Custom Caravan Escorts (Armed)", "Keltian Steppe Caravan Company", 0.25, "contracts"},
	{"Steppe Route Navigation Charts", "Keltian Steppe Caravan Company", 1.1, "scrolls"},
	{"Water Cache Delivery Refills", "Keltian Steppe Caravan Company", 0.46, "loads"},
	{"Salt Brick Exports (Packaged for Caravan)", "Keltian Steppe Caravan Company", 0.75, "blocks"},
	{"Dry Ridge Campground Leasing (Seasonal)", "Keltian Steppe Caravan Company", 3.5, "stations"},
	{"Pilgrim Caravans (Sacred Route Access)", "Keltian Steppe Caravan Company", 0.35, "convoys"},
	{"Seal of Safe Crossing (Alperkin Stamp)", "Keltian Steppe Caravan Company", 0.05, "marks"},
	{"Cross-Winds Risk Insurance (Tonar-Bashkim)", "Keltian Steppe Caravan Company", 0.29, "policies"},

	{"Iron Ingots (Refined)", "Sårensby Depot", 1.45, "tons"},
	{"Copper Scrap Bundles", "Sårensby Depot", 0.88, "crates"},
	{"Rare-Earth Ore Fragments", "Sårensby Depot", 2.3, "satchels"},
	{"Frozen Reindeer Cuts", "Sårensby Depot", 0.67, "packages"},
	{"Cured Reindeer Leather", "Sårensby Depot", 1.15, "hides"},
	{"Seal Fur Pelts", "Sårensby Depot", 2.8, "rolls"},
	{"Reindeer Antler Tools", "Sårensby Depot", 0.42, "sets"},
	{"Wool Blankets (Nordic Pattern)", "Sårensby Depot", 0.39, "bundles"},
	{"Smoked Elk Sausages", "Sårensby Depot", 0.51, "links"},
	{"Pickled Arctic Herring", "Sårensby Depot", 0.6, "jars"},
	{"Salted Cod (Barrel Aged)", "Sårensby Depot", 0.83, "barrels"},
	{"Smoked Goose Breast", "Sårensby Depot", 0.49, "cuts"},
	{"Seal Oil Lantern-Grade", "Sårensby Depot", 0.73, "flasks"},
	{"Whale Bone (Industrial Grade)", "Sårensby Depot", 1.95, "pieces"},
	{"Blubber Oil (Purified)", "Sårensby Depot", 1.2, "casks"},
	{"Wild Berry Preserves", "Sårensby Depot", 0.34, "jars"},
	{"Lingonberry Jam (Sweetened)", "Sårensby Depot", 0.27, "jars"},
	{"Conifer Lumber", "Sårensby Depot", 1.1, "planks"},
	{"Processed Granite Slabs", "Sårensby Depot", 1.7, "tiles"},
	{"Reindeer Jerky Trail Packs", "Sårensby Depot", 0.23, "packs"},
	{"Caledonian Cured Ham", "Sårensby Depot", 6.9, "hams"},
	{"Sturgeon Caviar", "Sårensby Depot", 9.8, "tins"},
	{"Frozen Whitefish Fillets", "Sårensby Depot", 0.64, "trays"},
	{"Processed Wild Duck Feathers", "Sårensby Depot", 0.36, "bundles"},

	{"Harbor Transit Pilotage (per vessel)", "Haifa Compliance Exchange", 0.80, "transits"},
	{"Compliance Bonds (standard issue)", "Haifa Compliance Exchange", 0.25, "bonds"},
	{"Documentation Services (cargo manifest)", "Haifa Compliance Exchange", 0.45, "filings"},
	{"Inspection Scheduling (priority slot)", "Haifa Compliance Exchange", 0.35, "slots"},
	{"Port Entry Clearance Certificates", "Haifa Compliance Exchange", 0.55, "certificates"},
	{"Breach Risk Arbitration (per case)", "Haifa Compliance Exchange", 1.20, "cases"},
	{"Escort Assignment Mediation (War League/Hatch)", "Haifa Compliance Exchange", 0.65, "agreements"},
	{"Emergency Compliance Hearings", "Haifa Compliance Exchange", 0.95, "hearings"},
	{"Cargo Seal Verification (War League Escort)", "Haifa Compliance Exchange", 0.55, "checks"},
	{"Sacred Buffer Compliance Certificates", "Haifa Compliance Exchange", 0.46, "stamps"},
	{"Environmental Buffer Routing Plans", "Haifa Compliance Exchange", 0.62, "charts"},
	{"Emergency Leviathan Protocol Insurance", "Haifa Compliance Exchange", 1.7, "policies"},
	{"Search-and-Rescue Priority Registration", "Haifa Compliance Exchange", 0.83, "slots"},
	{"Anchorage Review Mediation (Expedited)", "Haifa Compliance Exchange", 0.95, "hearings"},
	{"Daily Enforcement Report Subscription", "Haifa Compliance Exchange", 0.22, "issues"},

	{"Freight Handling (per ton)", "Port of Corumia", 1.80, "tons"},
	{"Harbor Pilotage (per transit)", "Port of Corumia", 5.30, "transits"},
	{"Drydock Berth (per day)", "Port of Corumia", 16.60, "days"},
	{"Tug Assist (harbor move)", "Port of Corumia", 3.20, "moves"},
	{"Customs Brokerage (filing)", "Port of Corumia", 1.850, "filings"},
	{"Bonded Warehousing", "Port of Corumia", 0.52, "m³·day"},
	{"Cold Storage", "Port of Corumia", 0.68, "m³·day"},
	{"Security Escort (quay-to-gate)", "Port of Corumia", 1.85, "escorts"},
	{"Quarantine Inspection (vessel)", "Port of Corumia", 2.70, "vessels"},
	{"Medical Clearance (per crew)", "Port of Corumia", 0.66, "crew"},

	{"Vessel Berth Window (per hour reserved)", "Pentiad Terminal Operations", .340, "hours"},
	{"Quay Crane Move (per container)", "Pentiad Terminal Operations", .150, "moves"},
	{"Breakbulk Stevedoring (per ton)", "Pentiad Terminal Operations Agency", .110, "tons"},
	{"Gate Processing Fee (per truck visit)", "Pentiad Terminal Operations", .055, "visits"},
	{"Dry Yard Storage (per TEU·day)", "Pentiad Terminal Operations", .040, "TEU·day"},
	{"Demurrage (per TEU·day beyond free time)", "Pentiad Terminal Operations", 0.80, "TEU·day"},
	{"Reefer Plug-In (per container·day)", "Pentiad Terminal Operations", .090, "container·day"},
	{"Reefer Temperature Monitoring (per container·day)", "Pentiad Terminal Operations", .060, "container·day"},
	{"Rail Intermodal Transfer (per TEU)", "Pentiad Terminal Operations", .145, "TEU"},
	{"Barge Transfer (per TEU)", "Pentiad Terminal Operations", .115, "TEU"},

	{"Escort Tug (Inbound Transit)", "Azat Tug and Pilot Cooperative", .240, "moves"},
	{"Escort Tug (Outbound Transit)", "Azat Tug and Pilot Cooperative", .240, "moves"},
	{"Azat Line Boat Support (Mooring/Unmooring)", "Azat Tug and Pilot Cooperative", .170, "deployments"},
	{"Tug Assist (Turning Basin Maneuver)", "Azat Tug and Pilot Cooperative", .200, "maneuvers"},
	{"Emergency Tow Response (Flat Rate)", "Azat Tug and Pilot Cooperative", .680, "responses"},
	{"Pilot Dispatch Cancellation Fee", "Azat Tug and Pilot Cooperative", .120, "cancellations"},
	{"Pilotage Slot Reservation (Peak Hours)", "Azat Tug and Pilot Cooperative", .260, "reservations"},
	{"Multi-Vessel Convoy Guidance (Straits)", "Azat Tug and Pilot Cooperative", .510, "convoys"},
	{"War-Risk Tug Escort (Haifa Exclusion Zone)", "Azat Tug and Pilot Cooperative", .700, "escort moves"},
	{"Docking Delay Standby Fee (per 30 minutes)", "Azat Tug and Pilot Cooperative", .150, "intervals"},

	{"Hull Inspection and Ultrasonic Survey", "Calliope Shipyard Repair Agency", .360, "calls"},
	{"Routine Hull Patching (Standard Plate)", "Calliope Shipyard Repair Agency", .580, "repairs"},
	{"Dry Dock Berth (per day)", "Calliope Shipyard Repair Agency", .1600, "days"},
	{"Propulsion Shaft Alignment (Standard Class)", "Calliope Shipyard Repair Agency", .720, "alignments"},
	{"Ballast Tank Cleaning and Recoating", "Calliope Shipyard Repair Agency", .850, "jobs"},
	{"Emergency Weld Team Dispatch", "Calliope Shipyard Repair Agency", .490, "calls"},
	{"Underwater ROV Survey (Sub-10m Draft)", "Calliope Shipyard Repair Agency", .660, "surveys"},
	{"Deck Equipment Overhaul (Winches & Davits)", "Calliope Shipyard Repair Agency", .440, "units"},

	{"Hull War-Risk Coverage (Standard)", "Bulhanu Maritime Insurance Association", .120, "policies"},
	{"Cargo Delay Coverage (per day)", "Bulhanu Maritime Insurance Association", .065, "days"},
	{"Piracy & Seizure War-Risk Rider", "Bulhanu Maritime Insurance Association", .180, "riders"},
	{"Blockade Transit Risk Certificate", "Bulhanu Maritime Insurance Association", .210, "certificates"},
	{"Salvage Claim Arbitration Package", "Bulhanu Maritime Insurance Association", .155, "cases"},
	{"Crew Loss & Injury Indemnity", "Bulhanu Maritime Insurance Association", .095, "policies"},
	{"Port Authority Liability Coverage", "Bulhanu Maritime Insurance Association", .110, "policies"},
	{"Storm-Transit Hazard Rider (seasonal)", "Bulhanu Maritime Insurance Association", .130, "riders"},
	{"Host-Star Auspice Risk Review (premium)", "Bulhanu Maritime Insurance Association", .175, "reviews"},
	{"Voyage Cancellation Refund Guarantee", "Bulhanu Maritime Insurance Association", .240, "guarantees"},
	{"Crew Repatriation & Illness Indemnity", "Bulhanu Maritime Insurance Association", .190, "policies"},
	{"Charter Party Breach Risk Mitigation (Vaeringheim Court)", "Bulhanu Maritime Insurance Association", .450, "agreements"},
	{"Marine Arbitration Retainer (Tier II Cases)", "Bulhanu Maritime Insurance Association", .210, "retainers"},

	{"Customs Clearance Filing (Standard Entry)", "Morovian Customs & Freight Syndicate", 1.10, "filings"},
	{"Tariff Classification Advisory (per commodity)", "Morovian Customs & Freight Syndicate", 0.60, "consultations"},
	{"Bonded Warehouse Transfer (Inward Entry)", "Morovian Customs & Freight Syndicate", 0.80, "transfers"},
	{"Freight Forwarding (Port-to-Gate, Domestic)", "Morovian Customs & Freight Syndicate", 1.50, "contracts"},
	{"Freight Forwarding (Cross-Straits, Interport)", "Morovian Customs & Freight Syndicate", 2.90, "contracts"},
	{"Cargo Consolidation (LCL Containerized)", "Morovian Customs & Freight Syndicate", 1.40, "shipments"},
	{"Cargo Deconsolidation & Palletization", "Morovian Customs & Freight Syndicate", 1.10, "shipments"},
	{"Duty Suspension Arrangement (Transit Cargo)", "Morovian Customs & Freight Syndicate", 0.95, "agreements"},
	{"Customs Escort Assignment (Risk Tier II+)", "Morovian Customs & Freight Syndicate", 1.85, "assignments"},
	{"Import License Facilitation (Non-Standard Goods)", "Morovian Customs & Freight Syndicate", 2.10, "licenses"},
	{"Voucher Redemption Processing (Cultic Commodities)", "Morovian Customs & Freight Syndicate", 1.75, "cases"},
	{"Sanctioned Cargo Screening Compliance Report", "Morovian Customs & Freight Syndicate", 2.60, "reports"},

	{"Sanitation Pump-Out (per vessel)", "Morovian Sanitation and Bilge Company", .320, "vessels"},
	{"Bilge Extraction & Treatment (per m³)", "Morovian Sanitation and Bilge Company", .070, "m³"},
	{"Hazardous Waste Containment (sealed drum)", "Morovian Sanitation and Bilge Company", .180, "drums"},
	{"Quarantine Decontamination Washdown", "Morovian Sanitation and Bilge Company", .450, "washdowns"},
	{"Sewage Sludge Disposal (per ton)", "Morovian Sanitation and Bilge Company", .090, "tons"},
	{"Mosquito Abatement Fumigation (district)", "Morovian Sanitation and Bilge Company", .240, "districts"},
	{"Canal Biofilm Scrape & Flush (per km)", "Morovian Sanitation and Bilge Company", .150, "km"},
	{"Dockside Latrine Service (per unit·day)", "Morovian Sanitation and Bilge Company", .028, "unit·day"},
	{"Waste Sorting & Removal (per m³)", "Morovian Sanitation and Bilge Company", .045, "m³"},
	{"Medical Waste Incineration (per kg)", "Morovian Sanitation and Bilge Company", .065, "kg"},
	{"Emergency Spill & Contamination Response (flat rate)", "Morovian Sanitation and Bilge Company", .720, "responses"},
	{"Wastewater Pathogen Monitoring (per assay)", "Morovian Sanitation and Bilge Company", .125, "assays"},
	{"Cistern Shock Chlorination (per cistern)", "Morovian Sanitation and Bilge Company", .050, "cisterns"},
	{"Potable-Water Chlorination Dosing & Certification (per 100 m³)", "Morovian Sanitation and Bilge Company", .040, "100 m³"},
	{"Food-Handler Hygiene Audits & Licensing (per kitchen·stall)", "Morovian Sanitation and Bilge Company", .065, "inspections"},
	{"Rodent Trap Deployment & Monitoring (per trap·month)", "Morovian Sanitation and Bilge Company", .022, "months"},
	{"Hand-Wash Station Deployment & Service (per unit·day)", "Morovian Sanitation and Bilge Company", .030, "unit·day"},

	{"Highland Route Guidance (Merchant Convoy Escort)", "Ordo Ebríumä Oneira (Highland Guides)", 2.80, "routes"},
	{"Pilgrim Procession Escort (Seasonal)", "Ordo Ebríumä Oneira (Highland Guides)", 1.45, "processions"},
	{"Ridge Ropeway Licensing & Certification", "Ordo Ebríumä Oneira (Highland Guides)", 3.10, "licenses"},
	{"Avalanche Risk Survey & Signage", "Ordo Ebríumä Oneira (Highland Guides)", 2.60, "surveys"},
	{"Highland Rescue Team Dispatch (Emergency)", "Ordo Ebríumä Oneira (Highland Guides)", 4.90, "responses"},
	{"Pack Stock Portage (Caravan Animals Included)", "Ordo Ebríumä Oneira (Highland Guides)", 3.25, "contracts"},
	{"Cairn and Trail Maintenance (Vow Renewal Service)", "Ordo Ebríumä Oneira (Highland Guides)", 1.75, "sites"},
	{"Tar-Lamp Night Vigil Coverage", "Ordo Ebríumä Oneira (Highland Guides)", 0.85, "nights"},
	{"Stone-Reader Boundary Arbitration", "Ordo Ebríumä Oneira (Highland Guides)", 1.10, "hearings"},
	{"Eclipse Silent-Watch Contract (Seasonal Oath)", "Ordo Ebríumä Oneira (Highland Guides)", 1.30, "events"},

	{"Haifan Mainline Sky-Berth (Lykopolis–Lewisburg)", "Lothayan Skybridge Airways", .95, "berths"},
	{"Haifan Branchline Pilgrim Berth (Tel-Amin–Diamandis–Thermosalem)", "Lothayan Skybridge Airways", .770, "berths"},
	{"Haifan Littoral Cargo Lift (Lykopolis–Sufriya–Mylecia)", "Lothayan Skybridge Airways", .410, "tons"},
	{"Keybir-Aviv–Tel-Amin–Jogi–Abeis–Blore Heath Coastal Mail Loop", "Lothayan Skybridge Airways", .230, "contracts"},
	{"Somniumpolis–Odiferian Highlands Tribal Freight", "Lothayan Skybridge Airways", .450, "tons"},
	{"Somniumpolis–Aureum–Erythros Long-Range Sky-Berth", "Lothayan Skybridge Airways", .135, "berths"},
	{"Erythros–Pyralis Alpine Connector Passenger & Freight Line", "Lothayan Skybridge Airways", .110, "berths"},
	{"Erythros–Nexa–Delphica–Saluria Shrine Pilgrimage Berth", "Lothayan Skybridge Airways", .105, "berths"},
	{"Acheron–Koinonía–Sylvapolis Canyonlands Night Tour", "Lothayan Skybridge Airways", .120, "tours"},
	{"Vaeringheim–Luminaria–Jezeraah City Dawnliner Passenger Berth", "Lothayan Skybridge Airways", .110, "berths"},
	{"Symphonara–Delphica–Aurelia–Serena Cultural Circuit Cabin", "Lothayan Skybridge Airways", .180, "cabins"},
	{"Lunalis Sancta–Catonis Atrium Ecclesiastical Charter", "Lothayan Skybridge Airways", .590, "charters"},
	{"Vaeringheim–Ferrum Citadel Industrial Sky-Freight", "Lothayan Skybridge Airways", .475, "tons"},
	{"Skýrophos–Pelagia Fjordline Passenger Berth", "Lothayan Skybridge Airways", .105, "berths"},
	{"Norsolyra–Thorsalon–Rein Harvest Vintage Passenger Line", "Lothayan Skybridge Airways",.115, "berths"},
	{"Bjornopolis–Aegirheim–Ephyra–Myrene Highlands Passenger & Mail Service", "Lothayan Skybridge Airways", .120, "berths"},
	{"Riddersborg–Ardclach–Redcliff Citadel Normark Passenger Aerial Ferry", "Lothayan Skybridge Airways", .105, "berths"},
	{"Ourid–Caspazani–Aetherium Agricultural Worker Passenger Line", "Lothayan Skybridge Airways", .125, "berths"},
	{"Sårensby–Elijah’s Rest Trans-Keltian Diplomatic Charter", "Lothayan Skybridge Airways", .690, "charters"},
	{"Slevik–Suncliff–Somniumpolis Coastal Connector Sky-Berth", "Lothayan Skybridge Airways", .125, "berths"},
	{"Haifan Armored Lake Dolphin Training (basic)", "Nefelean Seas Armory", 0.55, "courses"},
	{"Handler Team (certified) – daily service", "Nefelean Seas Armory", 0.22, "days"},
	{"Reconnaissance Patrol (armored dolphin pair)", "Nefelean Seas Armory", 0.35, "patrols"},
	{"Escort Run (convoy / VIP transit)", "Nefelean Seas Armory", 0.48, "escorts"},
	{"Harbor Defense Shift (night watch)", "Nefelean Seas Armory", 0.60, "shifts"},
	{"Armor Fitting & Sealant Service (dolphin harness)", "Nefelean Seas Armory", 0.25, "fits"},
	{"Hydrophone Sweep & Echolocation Mapping", "Nefelean Seas Armory", 0.32, "sweeps"},
	{"Rapid Intercept / Deterrence Callout", "Nefelean Seas Armory", 0.75, "callouts"},

}

---------------------------------------------------------
-- City-Signal Integrations
---------------------------------------------------------
local forecastOk, forecast = pcall(require, "Module:BassaridiaForecast")
local hatchOk, hatch = pcall(require, "Module:HatchMinistryDailyOps")
local outbreakOk, outbreaks = pcall(require, "Module:BassaridiaOutbreaks")
local warOk, war = pcall(require, "Module:WarLeagueDivisionOpsBVR")

local function escapePattern(s)
	s = tostring(s or "")
	return s:gsub("([%%%^%$%(%)%.%[%]%*%+%-%?])", "%%%1")
end

local function normalizeCompany(company)
	company = tostring(company or "")
	company = company:gsub("%s+$", "")
	company = company:gsub("%*$", "")
	company = company:gsub("%s+$", "")
	return company
end

local companyHQOverrides = {
	["Hatch Ministry"] = "Vaeringheim",
	["Lake Morovia Blockade Fund - Hatch Ministry"] = "Vaeringheim",
	["Maritime Guild of the Cult of Maskmakers"] = "Jogi",
	["Ergonian Spy Agency"] = "Jogi",
	["Temple Bank of the Reformed Stripping Path"] = "Vaeringheim",
	["Couriers of the Lizard Queen"] = "Delphica",
	["Temple University of Delphica"] = "Delphica",
	["La Sái Ebile"] = "Erythros",
	["Trans-Morovian Express"] = "Riddersborg",
	["Hellhound Breeders of Dragevik"] = "Dragevik",
	["Pharmacon Sect"] = "Acheron",
	["Skyrophian Security Contractors"] = "Skýrophos",
	["Haifadora Postal Service"] = "Vaeringheim",
	["Fleet of Rouge Divers"] = "Rouge",
	["Merchant Caravans of the Candy Kingdom"] = "Butterscotch",
	["Bassaridian Broadcasting Corporation"] = "Vaeringheim",
	["Temple of Aprobelle"] = "Vaeringheim",
	["Keltian Steppe Caravan Company"] = "Tonar",
	["Sårensby Depot"] = "Sårensby",
	["Haifa Compliance Exchange"] = "Vaeringheim",
	["Port of Corumia"] = "",
	["Pentiad Terminal Operations"] = "Vaeringheim",
	["Pentiad Terminal Operations Agency"] = "Vaeringheim",
	["Azat Tug and Pilot Cooperative"] = "Vaeringheim",
	["Calliope Shipyard Repair Agency"] = "Vaeringheim",
	["Bulhanu Maritime Insurance Association"] = "Vaeringheim",
	["Morovian Customs & Freight Syndicate"] = "Vaeringheim",
	["Morovian Sanitation and Bilge Company"] = "Vaeringheim",
	["Ordo Ebríumä Oneira (Highland Guides)"] = "",
	["Lothayan Skybridge Airways"] = "Vaeringheim",
}

local function inferHQCity(companyName)
	local c = normalizeCompany(companyName)
	return companyHQOverrides[c] or ""
end

local function clamp(x, lo, hi)
	if x < lo then return lo end
	if x > hi then return hi end
	return x
end

local function opsLevelToNumber(levelOrLabel)
	local n = tonumber(levelOrLabel)
	if n then return n end
	local t = tostring(levelOrLabel or ""):lower()
	if t:find("green") then return 0 end
	if t:find("yellow") then return 1 end
	if t:find("orange") then return 2 end
	if t:find("red") then return 3 end
	return 0
end

local function productClassServ(productName, companyName)
	local n = tostring(productName or ""):lower()
	local c = normalizeCompany(companyName):lower()

	if n:find("sanitation") or n:find("bilge") or n:find("quarantine") or n:find("decontamination")
		or n:find("medical") or n:find("pathogen") or n:find("chlorination") or n:find("hygiene") or n:find("abatement")
		or n:find("customs") or n:find("clearance") or n:find("tariff") or n:find("bonded") or n:find("freight")
		or n:find("pilotage") or n:find("tug") or n:find("berth") or n:find("stevedoring") or n:find("intermodal")
		or n:find("escort") or n:find("security") or n:find("risk") or n:find("insurance") or n:find("arbitration")
		or n:find("postal") or n:find("delivery") or n:find("courier")
		or c:find("sanitation") or c:find("customs") or c:find("insurance") or c:find("terminal") or c:find("tug")
	then
		return "essential"
	end

	if c:find("aprobelle") or n:find("loyalty") or n:find("behavior") or n:find("polygraph") or n:find("anomaly") then
		return "governance"
	end

	if n:find("circus") or n:find("performance") or n:find("parade") or n:find("tickets") or n:find("tour")
		or n:find("cabin") or n:find("luxury") or n:find("advert") or n:find("sponsorship") or n:find("broadcast")
		or n:find("salvaged") or n:find("antique") or n:find("treasure") or n:find("jewelry") or n:find("artifact")
		or c:find("divers") or c:find("candy") or c:find("broadcasting")
	then
		return "discretionary"
	end

	if c:find("hatch ministry") or c:find("blockade fund") then
		return "volatile"
	end

	return "standard"
end

-- Cache tables (filled per generateTable call)
local cache = {
	forecast = {},   -- city -> {mult,note,opsLevel}
	war = {},        -- city -> {mult,note} (depends on opsLevel + war count)
	hatchCount = {}, -- city -> integer
	health = {},     -- city -> {mult,severity,note}
}

local function getForecastSignal(city, year, dayOfYear)
	local v = cache.forecast[city]
	if v then return v end

	if not (forecastOk and forecast and type(forecast.getOpsData) == "function") then
		v = { mult = 0, note = nil, opsLevel = 0 }
		cache.forecast[city] = v
		return v
	end

	local op = forecast.getOpsData(city, year, dayOfYear)
	if not op or not op.alert or not op.impacts then
		v = { mult = 0, note = nil, opsLevel = 0 }
		cache.forecast[city] = v
		return v
	end

	local m = 0
	local ground = tostring(op.impacts.ground or "OK")
	local sea    = tostring(op.impacts.sea or "OK")
	local air    = tostring(op.impacts.air or "OK")

	if ground == "Slow" then m = m + 0.02
	elseif ground == "Closed" then m = m + 0.08 end

	if sea == "Restricted" then m = m + 0.03
	elseif sea == "Closed" then m = m + 0.06 end

	if air == "Limited" then m = m + 0.01
	elseif air == "No-Go" then m = m + 0.04 end

	local cond = tostring(op.condition or "")
	local lc = cond:lower()
	if lc:find("blizzard") then m = m + 0.05
	elseif lc:find("storm") then m = m + 0.03
	elseif lc:find("fog") then m = m + 0.02
	elseif lc:find("rain") then m = m + 0.01 end

	local opsLevel = opsLevelToNumber(op.alert.level)
	local note = string.format("WX/Ops %s (%s; G:%s S:%s A:%s)", tostring(op.alert.label or ""), cond, ground, sea, air)

	v = { mult = m, note = note, opsLevel = opsLevel }
	cache.forecast[city] = v
	return v
end

-- Precompute hatch city counts once (one report render + per-city pattern counts only for cities we need)
local hatchReportText = nil
local function getHatchCityCount(city, year, dayOfYear)
	local v = cache.hatchCount[city]
	if v ~= nil then return v end

	if not hatchReportText then
		if hatchOk and hatch and type(hatch.dailyReport) == "function" then
			hatchReportText = tostring(hatch.dailyReport({ args = { year = tostring(year), day = tostring(dayOfYear), legend = "no" } }) or "")
		else
			hatchReportText = ""
		end
	end

	local needle = "%[%[List_of_cities_in_Bassaridia_Vaeringheim#" .. escapePattern(city) .. "%|" .. escapePattern(city) .. "%]%]"
	local c = 0
	for _ in hatchReportText:gmatch(needle) do c = c + 1 end
	cache.hatchCount[city] = c
	return c
end

local warTableText = nil
local function getWarCityCount(city, year, dayOfYear)
	-- store under hatchCount? no; just compute per city using warTableText, but keep as cache.warCount
	cache.warCount = cache.warCount or {}
	local v = cache.warCount[city]
	if v ~= nil then return v end

	if not warTableText then
		if warOk and war and type(war.makeTable) == "function" then
			warTableText = tostring(war.makeTable({ args = { rows = "48", showlegend = "no", seed = tostring(year * 1000 + dayOfYear) } }) or "")
		else
			warTableText = ""
		end
	end

	local needle = "%[%[List_of_cities_in_Bassaridia_Vaeringheim#" .. escapePattern(city) .. "%|" .. escapePattern(city) .. "%]%]"
	local c = 0
	for _ in warTableText:gmatch(needle) do c = c + 1 end
	cache.warCount[city] = c
	return c
end

local function getHatchSignal(city, year, dayOfYear)
	local n = getHatchCityCount(city, year, dayOfYear)
	if n <= 0 then return { mult = 0, note = nil } end
	local m = math.min(0.05, n * 0.005)
	return { mult = m, note = string.format("Hatch activity %d (≈+%.1f%%)", n, m*100) }
end

local function parseOutbreakSeverity(outText)
	outText = tostring(outText or "")
	local sev = outText:match('style="background:[^"]+"%s*|%s*([A-Z]+)%s*||')
	if sev == "CRITICAL" or sev == "HIGH" or sev == "MEDIUM" or sev == "LOW" or sev == "NONE" then
		return sev
	end
	return "NONE"
end

local function getHealthSignal(city)
	local v = cache.health[city]
	if v then return v end

	if not (outbreakOk and outbreaks and type(outbreaks.outbreaksForCity) == "function") then
		v = { mult = 0, severity = "NONE", note = nil }
		cache.health[city] = v
		return v
	end

	local txt = outbreaks.outbreaksForCity({ args = { city = city } })
	local sev = parseOutbreakSeverity(txt)

	local m = 0
	if sev == "LOW" then m = 0.01
	elseif sev == "MEDIUM" then m = 0.03
	elseif sev == "HIGH" then m = 0.06
	elseif sev == "CRITICAL" then m = 0.10 end

	local note = (sev ~= "NONE") and ("Health " .. sev .. " (≈+" .. string.format("%.0f%%", m*100) .. ")") or nil
	v = { mult = m, severity = sev, note = note }
	cache.health[city] = v
	return v
end

local function getWarLeagueSignal(city, opsLevel, year, dayOfYear)
	-- war signal depends on opsLevel, so cache per city+opsLevel
	cache.war = cache.war or {}
	cache.war[city] = cache.war[city] or {}
	local v = cache.war[city][opsLevel]
	if v then return v end

	local m = 0
	if opsLevel == 1 then m = 0.01
	elseif opsLevel == 2 then m = 0.03
	elseif opsLevel >= 3 then m = 0.06 end

	local notes = {}
	if opsLevel > 0 then
		table.insert(notes, "War posture +" .. string.format("%.0f%%", m*100))
	end

	local c = getWarCityCount(city, year, dayOfYear)
	if c > 0 then
		local add = math.min(0.04, c * 0.003)
		m = m + add
		table.insert(notes, string.format("War League tempo %d (≈+%.1f%%)", c, add*100))
	end

	v = { mult = m, note = (#notes > 0) and table.concat(notes, "; ") or nil }
	cache.war[city][opsLevel] = v
	return v
end

local function getTempleBankSignal(pClass, healthSeverity, opsLevel)
	local crisis = (healthSeverity == "MEDIUM" or healthSeverity == "HIGH" or healthSeverity == "CRITICAL" or opsLevel >= 2)
	if not crisis then return { mult = 0, note = nil } end

	local m = 0
	if pClass == "essential" then
		if healthSeverity == "CRITICAL" then m = -0.04
		elseif healthSeverity == "HIGH" then m = -0.025
		else m = -0.015 end
		if opsLevel >= 3 then m = m - 0.01 end
		return { mult = m, note = string.format("Temple Bank stabilization (%.0f%%)", m*100) }
	elseif pClass == "governance" then
		if healthSeverity == "CRITICAL" or opsLevel >= 3 then m = 0.035
		elseif healthSeverity == "HIGH" or opsLevel >= 2 then m = 0.02
		else m = 0.01 end
		return { mult = m, note = string.format("Temple compliance demand (+%.0f%%)", m*100) }
	elseif pClass == "discretionary" then
		if healthSeverity == "CRITICAL" then m = 0.03
		elseif healthSeverity == "HIGH" then m = 0.02
		else m = 0.01 end
		return { mult = m, note = string.format("Temple market friction (+%.0f%%)", m*100) }
	else
		if opsLevel >= 3 or healthSeverity == "CRITICAL" then m = 0.02
		elseif opsLevel >= 2 or healthSeverity == "HIGH" then m = 0.01 end
		return { mult = m, note = (m ~= 0) and string.format("Temple finance friction (+%.0f%%)", m*100) or nil }
	end
end

---------------------------------------------------------
-- Special Date Events
---------------------------------------------------------
local events = {
	["1,6"]  = "Bayram al-Nur (Festival of Light) [Vaeringheim]",
	["1,18"] = "Chag Or Hadash (Festival of New Light) [Luminaria]",
	["1,30"] = "Symposion Eirinis (Symposium of Harmony) [Serena]",
	["1,43"] = "Alev Günü (Day of Flame) [Pyralis]",
	["1,48"] = "Day of Abandonment [Vaeringheim]",
	["1,55"] = "Tikkun Tzel (Repair of Shadows) [Symphonara]",
	["2,6"]  = "Panegyris Chrysou (Golden Gathering) [Aurelia]",
	["2,17"] = "Constitution Day [Luminaria]",
	["2,19"] = "Mehtap Dalgası (Moonlit Tide) [Vaeringheim]",
	["2,31"] = "Oneiro Foteino (Dream of Illumination) [Somniumpolis]",
	["2,39"] = "Anniversary of victory in the New South Jangsong Campaign [Nexa]",
	["2,44"] = "Erev Galgal (Eve of Cycles) [Nexa]",
	["2,45"] = "Bassaridia Festival [Somniumpolis]",
	["2,48"] = "Anniversary of victory in the Southern Lake Morovia Campaign [Somniumpolis]",
	["2,54"] = "Leilat al-Kamar (Night of the Moon) [Lunalis Sancta]",
	["2,61"] = "Taşrakah (Reverence of the Stone) [Luminaria]",
	["3,6"]  = "Chag Tvuah (Festival of Harvest) [Sylvapolis]",
	["3,18"] = "Anagenesis Eirmos (Procession of Rebirth) [Acheron]",
	["3,28"] = "Panagia Therizis (Holy Day of the Reaper) [Sylvapolis]",
	["3,37"] = "Anniversary of victory in the Morovian Frontier Campaign [Acheron]",
	["3,43"] = "Karnavali Thysias (Carnival of Celebration) [Erythros]",
	["3,53"] = "Sefar Yashar (Straight Path Celebration) [Catonis Atrium]",
}

---------------------------------------------------------
-- simulatePriceChange (same logic, but uses cached city signals)
---------------------------------------------------------
local function simulatePriceChange(basePrice, dayOfMonth, month, psscYear, dayOfYear, city, productName, companyName)
	local dateKey = string.format("%d,%d", month, dayOfMonth)

	local changeFactor = math.random(-20, 20) / 100
	local explanationParts = {}

	if events[dateKey] then
		table.insert(explanationParts, events[dateKey] .. ": Prices influenced by event dynamics")
		changeFactor = changeFactor + 0.05
	else
		table.insert(explanationParts, "General market fluctuations")
	end

	local cityAdd = 0
	local notes = {}

	city = tostring(city or "")
	if city ~= "" then
		local pClass = productClassServ(productName, companyName)

		local wx = getForecastSignal(city, psscYear, dayOfYear)
		cityAdd = cityAdd + (wx.mult or 0)
		if wx.note then table.insert(notes, wx.note) end

		local wl = getWarLeagueSignal(city, wx.opsLevel or 0, psscYear, dayOfYear)
		cityAdd = cityAdd + (wl.mult or 0)
		if wl.note then table.insert(notes, wl.note) end

		local hm = getHatchSignal(city, psscYear, dayOfYear)
		cityAdd = cityAdd + (hm.mult or 0)
		if hm.note then table.insert(notes, hm.note) end

		local ph = getHealthSignal(city)
		cityAdd = cityAdd + (ph.mult or 0)
		if ph.note then table.insert(notes, ph.note) end

		local tb = getTempleBankSignal(pClass, ph.severity or "NONE", wx.opsLevel or 0)
		cityAdd = cityAdd + (tb.mult or 0)
		if tb.note then table.insert(notes, tb.note) end
	end

	cityAdd = clamp(cityAdd, -0.20, 0.20)
	changeFactor = clamp(changeFactor + cityAdd, -0.35, 0.35)

	if #notes > 0 then
		table.insert(explanationParts, "Local signals: " .. table.concat(notes, "; "))
	end

	local explanation = table.concat(explanationParts, ". ") .. "."
	local newPrice = math.floor((basePrice * (1 + changeFactor)) * 100) / 100
	return newPrice, changeFactor, explanation
end

---------------------------------------------------------
-- determinePriceLevel
---------------------------------------------------------
local function determinePriceLevel(basePrice, adjustedPrice)
	if adjustedPrice > basePrice then
		return "Low"
	elseif adjustedPrice < basePrice then
		return "High"
	else
		return "Standard"
	end
end

---------------------------------------------------------
-- Args helpers
---------------------------------------------------------
local function getArgs(frame)
	if type(frame) ~= "table" then return {} end
	local args = {}
	local fargs = frame.args or {}
	local pargs = {}
	if frame.getParent then
		local parent = frame:getParent()
		if parent and parent.args then
			pargs = parent.args
		end
	end
	for k, v in pairs(pargs) do if v ~= nil and v ~= "" then args[k] = v end end
	for k, v in pairs(fargs) do if v ~= nil and v ~= "" then args[k] = v end end
	return args
end

local function isNo(v)
	v = tostring(v or ""):lower()
	return (v == "no" or v == "n" or v == "false" or v == "0")
end

local function levelSymbol(level)
	if level == "Low" then
		return "↑"
	elseif level == "High" then
		return "↓"
	else
		return "•"
	end
end

---------------------------------------------------------
-- generateTable (OPTIMIZED output building)
---------------------------------------------------------
function p.generateTable(frame)
	local args = getArgs(frame)
	local mode = tostring(args.mode or "both"):lower()
	local collapse = not isNo(args.collapse)
	local showSummary = (mode == "both" or mode == "summary")
	local showBreakdown = (mode == "both" or mode == "breakdown")

	-- Seed randomness per day
	local localTime = os.date("*t")
	local dailySeed = localTime.year * 1000 + localTime.yday
	math.randomseed(dailySeed)

	-- Date
	local dateString, dayOfMonth, month, psscYear, dayOfYear = getCurrentDate()

	-- Reset caches per invocation (avoid cross-page pollution)
	cache.forecast = {}
	cache.war = {}
	cache.warCount = {}
	cache.hatchCount = {}
	cache.health = {}
	hatchReportText = nil
	warTableText = nil

	-- Determine which unique cities we actually need (avoid scanning patterns for unused cities)
	local neededCities = {}
	for _, product in ipairs(products) do
		local _, company = product[1], product[2]
		local city = inferHQCity(company)
		if city and city ~= "" then
			neededCities[city] = true
		end
	end

	-- Warm up caches cheaply for each city (one outbreak call per city; one pattern scan per city)
	for city, _ in pairs(neededCities) do
		getForecastSignal(city, psscYear, dayOfYear)     -- cached
		getHatchCityCount(city, psscYear, dayOfYear)    -- cached (builds report once)
		getWarCityCount(city, psscYear, dayOfYear)      -- cached (builds table once)
		getHealthSignal(city)                           -- cached
	end

	local outParts = {}

	-- Summary header
	local summaryParts = {}
	if showSummary then
		table.insert(summaryParts, "{| class=\"wikitable sortable\"\n")
		table.insert(summaryParts, "! Date (Day/Month/Year [[PSSC]]) !! Δ !! Product !! Producing Company !! Tier I Price !! Units !! Notes\n")
	end

	-- Breakdown header
	local breakdownParts = {}
	if showBreakdown then
		local collapseClass = collapse and " mw-collapsible mw-collapsed" or ""
		table.insert(breakdownParts, "{| class=\"wikitable sortable" .. collapseClass .. "\"\n")
		table.insert(breakdownParts, "|+ Full tier breakdown" .. (collapse and " (click to expand)" or "") .. "\n")
		table.insert(breakdownParts, "! Date !! Product !! Producing Company !! Base Price !! Level !! Tier III !! Tier II !! Tier I !! Units !! Explanation\n")
	end

	local totalBase, totalNew, count = 0, 0, 0

	for _, product in ipairs(products) do
		local name, company, basePrice, units = unpack(product)
		local city = inferHQCity(company)

		local newPrice, _, explanation = simulatePriceChange(basePrice, dayOfMonth, month, psscYear, dayOfYear, city, name, company)
		local priceLevel = determinePriceLevel(basePrice, newPrice)
		local sym = levelSymbol(priceLevel)

		local rowStyle
		if priceLevel == "Low" then
			rowStyle = ' style="background-color:lightblue;"'
		elseif priceLevel == "Standard" then
			rowStyle = ' style="background-color:lightgreen;"'
		else
			rowStyle = ' style="background-color:#ffcccb;"'
		end

		local tierIIIPrice = math.floor((newPrice / 3) * 100) / 100
		local tierIIPrice  = math.floor((newPrice * 2 / 3) * 100) / 100
		local tierIPrice   = newPrice

		totalBase = totalBase + basePrice
		totalNew  = totalNew + newPrice
		count = count + 1

		if showSummary then
			table.insert(summaryParts, string.format(
				"|-%s\n| %s || %s || %s || %s || %.2f || %s || %s\n",
				rowStyle, dateString, sym, name, normalizeCompany(company), tierIPrice, units, explanation
			))
		end

		if showBreakdown then
			table.insert(breakdownParts, string.format(
				"|-%s\n| %s || %s || %s || %.2f || %s || %.2f || %.2f || %.2f || %s || %s\n",
				rowStyle, dateString, name, normalizeCompany(company), basePrice, priceLevel,
				tierIIIPrice, tierIIPrice, tierIPrice, units, explanation
			))
		end
	end

	local avgBase = totalBase / count
	local avgNew  = totalNew / count
	local avgLevel
	if avgNew > avgBase then
		avgLevel = "Low"
	elseif avgNew < avgBase then
		avgLevel = "High"
	else
		avgLevel = "Standard"
	end
	local avgSym = levelSymbol(avgLevel)

	if showSummary then
		table.insert(summaryParts, string.format(
			"|-\n! colspan=\"7\" | Average adjusted (%.2f) vs base (%.2f): %s %s\n|}\n",
			avgNew, avgBase, avgSym, avgLevel
		))
		table.insert(outParts, table.concat(summaryParts))
		table.insert(outParts, "\n")
	end

	if showBreakdown then
		table.insert(breakdownParts, string.format(
			"|-\n! colspan=\"10\" | Average adjusted (%.2f) vs base (%.2f): %s %s\n|}\n",
			avgNew, avgBase, avgSym, avgLevel
		))
		table.insert(outParts, table.concat(breakdownParts))
	end

	return table.concat(outParts)
end

function p.full(frame)
	frame = frame or {}
	frame.args = frame.args or {}
	frame.args.mode = "breakdown"
	frame.args.collapse = "no"
	return p.generateTable(frame)
end

return p