import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';

const here = new URL('./', import.meta.url);
const inventory = JSON.parse(await readFile(new URL('fastbtc-bitcoin-inventory.json', here), 'utf8'));
const assetMap = JSON.parse(await readFile(new URL('asset-map.json', here), 'utf8'));
const sources = JSON.parse(await readFile(new URL('sources.json', here), 'utf8'));

const BTC_SCALE = 8;
const USD_SCALE = 20;

function decimal(value, scale) {
  const [whole = '0', fraction = ''] = String(value).split('.');
  return BigInt(`${whole}${fraction.padEnd(scale, '0').slice(0, scale)}`);
}

function format(value, scale) {
  const raw = value.toString().padStart(scale + 1, '0');
  const whole = raw.slice(0, -scale) || '0';
  const fraction = raw.slice(-scale).replace(/0+$/, '');
  return `${whole}${fraction ? `.${fraction}` : ''}`;
}

const terminal = assetMap.addresses.bitcoinTerminalDeposit;
assert.equal(inventory.addressRoles[0].address, terminal, 'common terminal address');
const historicalStaging = inventory.addressRoles.find((entry) => entry.role === 'Historical FastBTC Bitcoin staging/operator wallet');
const rootstockStaging = inventory.addressRoles.find((entry) => entry.role === 'Rootstock peg-out staging address');
assert.equal(historicalStaging?.address, assetMap.addresses.fastBtcBitcoinStaging, 'historical staging/operator address');
assert.equal(rootstockStaging?.address, assetMap.addresses.bitcoinPowPegRecipient, 'Rootstock peg-out staging address');
assert.equal(inventory.totals.historicalStagingRetainedBTC, '0.45360411', 'excluded historical staging balance');
assert.equal(inventory.shutdownSweeps.length, 2, 'two direct Bitcoin-side shutdown sweeps');

let directInputs = 0n;
let directFees = 0n;
let directOutputs = 0n;
for (const sweep of inventory.shutdownSweeps) {
  const input = decimal(sweep.inputBTC, BTC_SCALE);
  const fee = decimal(sweep.feeBTC, BTC_SCALE);
  const output = decimal(sweep.terminalOutputBTC, BTC_SCALE);
  assert.equal(input - fee, output, `${sweep.id} input minus fee`);
  assert.equal(sweep.terminal, terminal, `${sweep.id} terminal`);
  directInputs += input;
  directFees += fee;
  directOutputs += output;
}
assert.equal(format(directInputs, BTC_SCALE), inventory.totals.bitcoinSideSweepInputsBTC);
assert.equal(format(directFees, BTC_SCALE), inventory.totals.bitcoinSideSweepFeesBTC);
assert.equal(format(directOutputs, BTC_SCALE), inventory.totals.bitcoinSideTerminalReceiptsBTC);

const replenisher = inventory.shutdownSweeps.find((sweep) => sweep.id === 'fastbtc-replenisher-sweep');
assert.ok(replenisher?.eventReconciliation, 'replenisher event reconciliation');
const events = replenisher.eventReconciliation;
assert.equal(
  events.exactNewBitcoinTransferIncomingInputCount + events.historicalOnlySameFamilyInputCount,
  events.historicalAddressUnionInputCount,
  'strict-event and historical-only inputs form the historical address union'
);
assert.equal(
  decimal(events.exactNewBitcoinTransferIncomingBTC, BTC_SCALE) + decimal(events.historicalOnlySameFamilyBTC, BTC_SCALE),
  decimal(events.historicalAddressUnionBTC, BTC_SCALE),
  'strict-event and historical-only value forms the historical address union'
);
assert.equal(
  events.exactNewBitcoinTransferIncomingInputCount +
    events.historicalOnlySameFamilyInputCount +
    events.samePolicyEventUnresolvedInputCount,
  replenisher.inputCount,
  'three provenance categories cover all replenisher inputs'
);
assert.equal(
  decimal(events.exactNewBitcoinTransferIncomingBTC, BTC_SCALE) +
    decimal(events.historicalOnlySameFamilyBTC, BTC_SCALE) +
    decimal(events.samePolicyEventUnresolvedBTC, BTC_SCALE),
  decimal(replenisher.inputBTC, BTC_SCALE),
  'three provenance categories cover the replenisher input value'
);

const mappedEvents = assetMap.fastBtcNovember.bitcoinSideShutdownSweeps.find(
  (sweep) => sweep.id === 'fastbtc-replenisher-sweep'
)?.eventReconciliation;
assert.equal(mappedEvents?.historicalOnlySameFamilyInputCount, events.historicalOnlySameFamilyInputCount);
assert.equal(mappedEvents?.historicalOnlySameFamilyBTC, events.historicalOnlySameFamilyBTC);

const rootstockOutputs = inventory.rootstockBranchTerminalReceipts.reduce(
  (total, receipt) => {
    assert.equal(receipt.from, rootstockStaging.address, `${receipt.tx} Rootstock staging source`);
    assert.equal(receipt.to, terminal, `${receipt.tx} terminal destination`);
    return total + decimal(receipt.amountBTC, BTC_SCALE);
  },
  0n
);
assert.equal(format(rootstockOutputs, BTC_SCALE), inventory.totals.rootstockBranchTerminalReceiptsBTC);
const shutdownTotal = directOutputs + rootstockOutputs;
assert.equal(format(shutdownTotal, BTC_SCALE), inventory.totals.combinedShutdownTerminalReceiptsBTC);
assert.equal(inventory.totals.combinedShutdownTerminalReceiptsBTC, assetMap.fastBtcNovember.totals.combinedShutdownTerminalDepositBTC);
assert.equal(
  shutdownTotal + decimal(inventory.totals.laterExchequerTerminalReceiptsBTC, BTC_SCALE),
  decimal(inventory.totals.observedFastBtcAndLaterExchequerReceiptsBTC, BTC_SCALE),
  'two-episode observed receipts'
);

let shutdownUsd = 0n;
for (const receipt of assetMap.tracedValueEstimate.fastBtcNovember.terminalReceipts) {
  const computed = decimal(receipt.amountBTC, BTC_SCALE) * decimal(receipt.candleCloseUSD, 2) * 10n ** 10n;
  assert.equal(computed, decimal(receipt.estimatedUSDExact, USD_SCALE), `${receipt.id} USD valuation`);
  shutdownUsd += computed;
  assert.ok(inventory.valuation.sourceIds.includes(receipt.sourceId), `${receipt.id} price source listed`);
}
assert.equal(shutdownUsd, decimal(inventory.valuation.estimatedUSDExact, USD_SCALE));
assert.equal(inventory.valuation.estimatedUSDRounded, assetMap.tracedValueEstimate.fastBtcNovember.shutdownUSDRounded);

const sourceIds = new Set(sources.map((source) => source.id));
for (const sourceId of [...inventory.sourceIds, ...inventory.valuation.sourceIds]) {
  assert.ok(sourceIds.has(sourceId), `known source ${sourceId}`);
}

const report = {
  status: 'verified',
  directBitcoinSideReceiptsBTC: inventory.totals.bitcoinSideTerminalReceiptsBTC,
  rootstockBranchReceiptsBTC: inventory.totals.rootstockBranchTerminalReceiptsBTC,
  combinedShutdownReceiptsBTC: inventory.totals.combinedShutdownTerminalReceiptsBTC,
  transferTimeUSD: inventory.valuation.estimatedUSDRounded,
  exactEventMatchedReplenisherBTC: events.exactNewBitcoinTransferIncomingBTC,
  historicalOnlySameFamilyReplenisherBTC: events.historicalOnlySameFamilyBTC,
  commonPolicyEventUnresolvedBTC: events.samePolicyEventUnresolvedBTC,
  historicalStagingRetainedBTC: inventory.totals.historicalStagingRetainedBTC,
  observedWithLaterExchequerReceiptsBTC: inventory.totals.observedFastBtcAndLaterExchequerReceiptsBTC
};

process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
