import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
const integer = (n, name, signed=false) => { if(!Number.isSafeInteger(n)||(!signed&&n<0))throw Error(`${name} must be safe integer cents`);return n; };
// Accumulate exact cents before checking the final Number range. Signed cancellation
// must not hide a rounded intermediate total or create a false reconciliation tie.
const sum = a => integer(Number(a.reduce((x,y)=>x+BigInt(integer(y,'amount',true)),0n)),'total',true);
const unique = (a,name) => { if(!Array.isArray(a)||!a.length||a.some(x=>typeof x!=='string'||!x)||new Set(a).size!==a.length)throw Error(`${name} requires unique nonempty identities`);return new Set(a); };
export function calculate(i) {
 if(i.fictional!==true||i.unit!=='USD cents')throw Error('Declare fictional inputs and USD cents');
 let result;
 switch(i.kind){
 case 'population': {
  const expected=unique(i.expected,'expected');const rows=new Map();
  for(const r of i.rows){if(!expected.has(r.id))throw Error('Out-of-scope row');integer(r.revenue,'revenue');if(r.cost!==null)integer(r.cost,'cost');if(rows.has(r.id)&&(rows.get(r.id).revenue!==r.revenue||rows.get(r.id).cost!==r.cost))throw Error('Conflicting duplicate');rows.set(r.id,r);}
  const missing=[...expected].filter(x=>!rows.has(x)),costMissing=[...rows.values()].filter(x=>x.cost===null).map(x=>x.id);
  result={rawRows:i.rows.length,distinctRows:rows.size,coveragePct:rows.size/expected.size*100,missing,costMissing,completeProfitCents:missing.length||costMissing.length?null:sum([...rows.values()].map(r=>r.revenue-r.cost))};break;
 }
 case 'settlement': {
  for(const k of ['gross','refunds','fees','notYetSettled','deposit'])integer(i[k],k);
  const expected=i.gross-i.refunds-i.fees-i.notYetSettled;if(expected<0)throw Error('Deductions exceed gross');result={expectedDepositCents:expected,differenceCents:i.deposit-expected,totalsTie:i.deposit===expected,transactionReconciliation:false};break;
 }
 case 'payroll': {
  for(const k of ['earned','booked','funding','fundingCredit','addedFeedExpense'])integer(i[k],k);
  if(i.fundingCredit>i.funding)throw Error('Credit exceeds funding');
  result={earnedMinusBookedCents:i.earned-i.booked,netFundingCents:i.funding-i.fundingCredit,possibleDuplicateExpenseCents:i.addedFeedExpense,decision:'Inspect service dates and existing journal before adding a bank-feed expense'};break;
 }
 case 'labor': {
  integer(i.payroll,'payroll');integer(i.overhead,'overhead');integer(i.budgetPayroll,'budgetPayroll');if(!Number.isFinite(i.budgetOperationalHours)||i.budgetOperationalHours<=0)throw Error('Budget hours must be positive');
  for(const k of ['paidHours','operationalHours','productiveHours'])if(!Number.isFinite(i[k])||i[k]<=0)throw Error('Hours must be positive');
  if(i.productiveHours>i.operationalHours||i.operationalHours>i.paidHours)throw Error('Hour populations are inconsistent');
  result={operationalHoursVariancePct:(i.operationalHours-i.budgetOperationalHours)/i.budgetOperationalHours*100,payrollVariancePct:(i.payroll-i.budgetPayroll)/i.budgetPayroll*100,budgetCostCentsPerOperationalHour:i.budgetPayroll/i.budgetOperationalHours,paidCostCentsPerHour:i.payroll/i.paidHours,operationalCostCentsPerHour:i.payroll/i.operationalHours,productiveCostCentsPerHour:sum([i.payroll,i.overhead])/i.productiveHours,pricingAssumption:'All declared overhead allocated to productive hours; not a payroll wage or observed quote rate'};break;
 }
 case 'linkage': {
  const expected=unique(i.expected,'expected'),linked=unique(i.linked,'linked'),costIds=unique(i.costs.map(x=>x.id),'costs');
  if([...linked,...costIds].some(x=>!expected.has(x)))throw Error('Out-of-scope identity');i.costs.forEach(x=>integer(x.cents,'cost'));
  result={linkagePct:[...expected].filter(x=>linked.has(x)).length/expected.size*100,missingCostIds:[...expected].filter(x=>!costIds.has(x)),profitAvailable:[...expected].every(x=>linked.has(x)&&costIds.has(x))};break;
 }
 case 'close': {
  if(typeof i.posted!=='boolean'||typeof i.protected!=='boolean')throw Error('Posting and protection need explicit evidence states');
  unique(i.items.map(x=>x.id),'close');for(const x of i.items){if(!['supported','estimate','source-needed'].includes(x.state))throw Error('Unknown acceptance state');if(x.state==='source-needed'){if(x.cents!==null)throw Error('Missing source cannot be zero');}else integer(x.cents,'close');if(x.state==='estimate'&&(typeof x.trueUp!=='string'||!x.trueUp.trim()))throw Error('Estimate needs true-up trigger');}
  result={supported:i.items.filter(x=>x.state==='supported').map(x=>x.id),estimates:i.items.filter(x=>x.state==='estimate').map(x=>x.id),sourceNeeded:i.items.filter(x=>x.state==='source-needed').map(x=>x.id),posted:i.posted===true,protected:i.protected===true,completeEvidence:i.items.every(x=>x.state!=='source-needed')};break;
 }
 case 'margin': {
  for(const k of ['revenue','labor','materials','unsoldInventory','laborMovedToOverhead'])integer(i[k],k);if(!i.revenue||i.laborMovedToOverhead>i.labor)throw Error('Invalid margin inputs');
  if(i.unsoldInventoryIncludedInMaterials!==false)throw Error('Declare the separate inventory scenario: unsold inventory is outside sold materials');
  const correct=i.revenue-i.labor-i.materials;const afterReclass=correct+i.laborMovedToOverhead;const afterReclassOperatingProfit=afterReclass-i.laborMovedToOverhead;const prematureBookProfit=correct-i.unsoldInventory;
  result={comparableGrossProfitCents:correct,apparentGrossProfitAfterReclassCents:afterReclass,companyProfitChangeFromReclassCents:afterReclassOperatingProfit-correct,bookProfitWithSeparateInventoryExpenseCents:prematureBookProfit,bookProfitAfterInventoryCorrectionCents:correct,profitDepressionFromPrematureInventoryExpenseCents:correct-prematureBookProfit,capitalizationCorrectionRaisesProfitCents:correct-prematureBookProfit,inventoryAssumption:'Separate purchase-period book scenario: unsold inventory was expensed outside the sold materials input; other operating expenses held at zero; not tax method advice'};break;
 }
 case 'identity': {
  for(const a of [i.bank,i.ledger]){unique(a.map(x=>x.id),'occurrences');for(const r of a){integer(r.cents,'signed',true);if(!/^\d{4}-\d{2}-\d{2}$/.test(r.date)||new Date(r.date).toISOString().slice(0,10)!==r.date)throw Error('Invalid occurrence date');}}
  const matched=i.bank.filter(b=>i.ledger.some(l=>b.id===l.id&&b.date===l.date&&b.cents===l.cents)).map(x=>x.id);
  result={totalsTie:sum(i.bank.map(x=>x.cents))===sum(i.ledger.map(x=>x.cents)),matchedIds:matched,unmatchedBank:i.bank.filter(x=>!matched.includes(x.id)).map(x=>x.id),unmatchedLedger:i.ledger.filter(x=>!matched.includes(x.id)).map(x=>x.id),decision:'Same amount and equal totals do not prove occurrence identity'};break;
 }
 default:throw Error('Unsupported evidence kind');
 }
 for(const [key,value] of Object.entries(result)){if(typeof value==='number'&&(!Number.isFinite(value)||Math.abs(value)>Number.MAX_SAFE_INTEGER))throw Error('Output exceeds safe numeric range');if(key.endsWith('Cents')&&value!==null)integer(value,key,true);}
 return {fictional:true,unit:i.unit,id:i.id,...result,limitation:'This is teaching arithmetic from supplied invented inputs, not source authenticity, financial assurance or authority to post.'};
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){if(!process.argv[2])throw Error('Usage: node reproduce.mjs package.input.json');console.log(JSON.stringify(calculate(JSON.parse(readFileSync(process.argv[2],'utf8'))),null,2));}
