import { readFile } from 'node:fs/promises'; const [file, ocid, ...extra] = process.argv.slice(2); if (!file || !ocid?.trim() || extra.length) { throw new Error('Usage: node prepare-tender-pair.mjs notices.json OCID'); } const rows = JSON.parse(await readFile(file, 'utf8')); if (!Array.isArray(rows)) throw new Error('Provide a JSON array of notice rows.'); const timestamp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/; const byId = new Map(); for (const row of rows) { if (row?.ocid !== ocid || row.source !== 'find-a-tender' || row.stage !== 'tender') continue; const { id, source, stage, publishedAt, title, tenderStatus, deadline } = row; if (typeof id !== 'string' || !id.trim() || typeof title !== 'string' || typeof tenderStatus !== 'string' || typeof publishedAt !== 'string' || !timestamp.test(publishedAt) || !Number.isFinite(Date.parse(publishedAt)) || (deadline !== null && typeof deadline !== 'string')) { throw new Error('Matching tender rows require an ID, title, status, publication timestamp, and deadline.'); } const notice = { ocid, id, source, stage, publishedAt, title, tenderStatus, deadline }; const prior = byId.get(id); if (prior && JSON.stringify(prior) !== JSON.stringify(notice)) { throw new Error(`Conflicting rows for notice ${id}.`); } byId.set(id, notice); } const notices = [...byId.values()].sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt)); if (notices.length < 2) throw new Error('The OCID needs at least two distinct tender notices.'); const [after_notice, before_notice, previous] = notices; if (Date.parse(after_notice.publishedAt) === Date.parse(before_notice.publishedAt) || (previous && Date.parse(before_notice.publishedAt) === Date.parse(previous.publishedAt))) { throw new Error('Publication times do not uniquely determine the newest two notices.'); } process.stdout.write(JSON.stringify({ before_notice, after_notice }) + '\n');