import {ELECTION_RULES,electionDates,electionWindow} from '../control-panel/public/election-rules.mjs'; import {ELECTIONS} from '../control-panel/public/political-catalog.mjs'; import {naibSeats} from './naib-membership.mjs'; export const PUBLIC_OFFICES=Object.freeze(ELECTIONS.map(e=>({key:({bene:'veiled_concord',guild:'spacing_guild','clan-delegate':'clan_delegate'})[e.id]||e.id,kind:e.kind,faction:e.faction,office:({naib_chair:'naib_chair',imperial:'emperor',house:'house_leader',bene:'reverent_mother',guild:'guild_leader',clan_delegate:'clan_delegate'})[e.kind],name:e.label,scope:e.kind==='naib_chair'?'Council of Naibs':e.kind==='house'?e.label.replace(' Leader',''):e.label,chamber:e.chamber,art:e.seal,description:e.chamber+' ยท Elected for four weeks.'}))); export function projectGovernment(terms,now=Date.now()){ return PUBLIC_OFFICES.map(office=>{ const ledgerKinds=office.kind==='bene'?['bene','house']:office.kind==='guild'?['guild','court']:[office.kind]; const active=terms.filter(t=>ledgerKinds.includes(t.kind)&&t.faction===office.faction&&t.office===office.office&&t.outcome==='winner'&&Number(t.starts_at)<=now&&Number(t.expires_at)>now); const term=active.length===1?active[0]:null; const holder=term&&/^[a-z0-9_]{3,32}$/i.test(term.username||'')?{username:term.username,name:term.display_name||term.username,profile:'/people/'+encodeURIComponent(term.username),avatar:'https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(term.username)}:null; return {...office,state:holder?'occupied':active.length?'verification_pending':'vacant',holder,term:holder?{startsAt:Number(term.starts_at),expiresAt:Number(term.expires_at)}:null}; }); } export function publicElectionCalendar(now=Date.now()){ return Object.keys(ELECTION_RULES).map(kind=>{ const dates=electionDates(kind,now-3*3600000,1),window=electionWindow(kind,dates[0],now); return {kind,...window,termWeeks:4}; }); } export async function readGovernmentOffices(db,now=Date.now()){ const rows=await db.prepare("SELECT t.kind,t.faction,t.office,t.starts_at,t.expires_at,t.outcome,a.username,a.display_name FROM political_office_terms t LEFT JOIN site_accounts a ON a.id=t.user_id AND a.password_hash NOT LIKE '!%' WHERE t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? ORDER BY t.starts_at DESC LIMIT 100").bind(now,now).all(); const terms=rows.results||[]; if(terms.some(t=>t.kind==='naib_chair')){const seats=await naibSeats(db),owners=new Set(seats.map(s=>s.username.toLowerCase()));return projectGovernment(terms.filter(t=>t.kind!=='naib_chair'||owners.has(String(t.username).toLowerCase())),now);} return projectGovernment(terms,now); } export function createPublicGovernment(db,{clock=Date.now}={}){return async request=>{ if(request.method!=='GET')return Response.json({message:'Read-only public office register.'},{status:405}); if(new URL(request.url).search)return Response.json({message:'No identity overrides are accepted.'},{status:400}); try{ const now=clock(),offices=await readGovernmentOffices(db,now); return Response.json({structure:{landsraad:['emperor','atreides','harkonnen','corrino','ordos'],realms:['atreides','harkonnen','corrino','ordos','fremen'],court:['veiled_concord','spacing_guild','clan_delegate'],chambers:[{name:'Imperial Senate',offices:['emperor','atreides','harkonnen','corrino','ordos']},{name:'Small Council',offices:['veiled_concord','spacing_guild','clan_delegate']}],clanAffiliation:'home_world',companiesBranch:'spacing_guild'},offices,elections:publicElectionCalendar(now),observedAt:now},{headers:{'Cache-Control':'public,max-age=30'}}); }catch{return Response.json({message:'The public office register is temporarily unavailable.'},{status:503,headers:{'Cache-Control':'no-store'}});} };}