#!/usr/bin/env node

/**
 * Independent verifier for /strata/quadratic-funding/.
 *
 * No values are imported from the page. Each result is derived here from the
 * definitions, then compared with a direct simulation of donor and donor-pair
 * contributions.
 */

let checks = 0;
let failures = 0;

function close(actual, expected, label, tolerance = 1e-11) {
  checks += 1;
  const scale = Math.max(1, Math.abs(actual), Math.abs(expected));
  const error = Math.abs(actual - expected);
  const ok = error <= tolerance * scale;
  console.log(`${ok ? "PASS" : "FAIL"} ${label}: actual=${actual} expected=${expected} error=${error}`);
  if (!ok) failures += 1;
}

function truth(condition, label, detail) {
  checks += 1;
  const ok = Boolean(condition);
  console.log(`${ok ? "PASS" : "FAIL"} ${label}: ${detail}`);
  if (!ok) failures += 1;
}

function directMatch(contributions) {
  let rootSum = 0;
  for (const contribution of contributions) rootSum += Math.sqrt(contribution);
  return rootSum ** 2;
}

function directPrincipal(contributions) {
  let total = 0;
  for (const contribution of contributions) total += contribution;
  return total;
}

function directSubsidy(contributions) {
  return directMatch(contributions) - directPrincipal(contributions);
}

function directNormalizedPayout(pool, projectDemands, targetIndex) {
  let totalDemand = 0;
  for (const demand of projectDemands) totalDemand += demand;
  return (pool * projectDemands[targetIndex]) / totalDemand;
}

function splitPot(n, C) {
  return Array.from({ length: n }, () => C / n);
}

function coefficientFromContributionVectors(M, a, b) {
  let overlap = 0;
  for (let p = 0; p < a.length; p += 1) {
    overlap += Math.sqrt(a[p]) * Math.sqrt(b[p]);
  }
  return M / (M + overlap);
}

function directPairwiseSubsidy(M, contributionVectors) {
  let total = 0;
  for (let i = 0; i < contributionVectors.length; i += 1) {
    for (let j = i + 1; j < contributionVectors.length; j += 1) {
      const coefficient = coefficientFromContributionVectors(
        M,
        contributionVectors[i],
        contributionVectors[j]
      );
      for (let p = 0; p < contributionVectors[i].length; p += 1) {
        total +=
          2 *
          coefficient *
          Math.sqrt(contributionVectors[i][p]) *
          Math.sqrt(contributionVectors[j][p]);
      }
    }
  }
  return total;
}

console.log("Quadratic funding independent verification");
console.log("");
console.log("1. Fixed-pot identity splits: (n sqrt(C/n))^2 = nC; subsidy = (n-1)C");

const splitCases = [
  [1, 100],
  [2, 100],
  [10, 100],
  [100, 100],
  [3, 7],
  [37, 250],
  [100, 1000],
];

for (const [n, C] of splitCases) {
  const contributions = splitPot(n, C);
  close(directPrincipal(contributions), C, `principal for n=${n}, C=${C}`);
  close(directMatch(contributions), n * C, `funding weight for n=${n}, C=${C}`);
  close(directSubsidy(contributions), (n - 1) * C, `subsidy for n=${n}, C=${C}`);
}

console.log("");
console.log("2. Two equal colluders: standard subsidy = 2W");

const attackW = [1, 10, 100, 1000, 1e6, 1e12];
for (const W of attackW) {
  const contributions = [W, W];
  close(directMatch(contributions), 4 * W, `two-account funding weight at W=${W}`);
  close(directSubsidy(contributions), 2 * W, `two-account subsidy at W=${W}`);
}

truth(
  directSubsidy([1e12, 1e12]) > directSubsidy([1e6, 1e6]),
  "standard attack grows beyond any tested finite scale",
  `subsidy(1e12)=${directSubsidy([1e12, 1e12])}`
);

console.log("");
console.log("3. Finite pools: normalize attack demand against other projects' demand H");

const normalizationCases = [
  [10000, 2, 10000],
  [10000, 200, 10000],
  [10000, 20000, 10000],
  [500000, 246.9, 100],
  [100, 2e6, 1e6],
];

for (const [pool, attackDemand, H] of normalizationCases) {
  const attackPayout = directNormalizedPayout(pool, [attackDemand, H], 0);
  const otherPayout = directNormalizedPayout(pool, [attackDemand, H], 1);
  const closed = (pool * attackDemand) / (attackDemand + H);
  close(
    attackPayout,
    closed,
    `normalized attack payout at pool=${pool}, demand=${attackDemand}, H=${H}`
  );
  close(
    attackPayout + otherPayout,
    pool,
    `normalized project payouts exhaust pool at pool=${pool}, demand=${attackDemand}, H=${H}`
  );
  truth(
    attackPayout < pool,
    `positive competing demand keeps attack payout below pool at demand=${attackDemand}, H=${H}`,
    `${attackPayout} < ${pool}`
  );
}

console.log("");
console.log("4. Pairwise-bounded pair: direct simulation = 2MW/(M+W), monotone, below 2M");

for (const M of [1, 10, 100, 1000]) {
  let previous = -Infinity;
  for (const W of [0.01, 1, 10, 100, 1000, 1e6, 1e12]) {
    const direct = directPairwiseSubsidy(M, [[W], [W]]);
    const closed = (2 * M * W) / (M + W);
    close(direct, closed, `pairwise pair at M=${M}, W=${W}`);
    truth(
      direct > previous,
      `pairwise pair is increasing at M=${M}, W=${W}`,
      `previous=${previous}, current=${direct}`
    );
    truth(
      direct < 2 * M,
      `pairwise pair stays below 2M at M=${M}, W=${W}`,
      `${direct} < ${2 * M}`
    );
    previous = direct;
  }
  const nearLimit = directPairwiseSubsidy(M, [[1e18], [1e18]]);
  close(nearLimit / (2 * M), 1, `pairwise pair approaches supremum 2M for M=${M}`, 1e-12);
}

console.log("");
console.log("5. Equal k-colluder groups: direct pair loop and k(k-1)MW/(M+W)");

for (const k of [2, 3, 5, 10, 20]) {
  for (const M of [10, 100]) {
    for (const W of [1, 100, 1e6]) {
      const vectors = Array.from({ length: k }, () => [W]);
      const direct = directPairwiseSubsidy(M, vectors);
      const closed = (k * (k - 1) * M * W) / (M + W);
      const ceiling = k * (k - 1) * M;
      close(direct, closed, `group total at k=${k}, M=${M}, W=${W}`);
      truth(
        direct < ceiling,
        `group stays below k(k-1)M at k=${k}, M=${M}, W=${W}`,
        `${direct} < ${ceiling}`
      );
    }
  }
}

console.log("");
console.log("6. Default page readouts");

const defaultW = 100;
const defaultM = 100;
const defaultK = 5;
const defaultPool = 10000;
const defaultHonestDemand = 10000;
const defaultRaw = directSubsidy([defaultW, defaultW]);
const defaultNormalizedPayout = directNormalizedPayout(
  defaultPool,
  [defaultRaw, defaultHonestDemand],
  0
);
const defaultPair = directPairwiseSubsidy(defaultM, [[defaultW], [defaultW]]);
const defaultGroup = directPairwiseSubsidy(
  defaultM,
  Array.from({ length: defaultK }, () => [defaultW])
);

close(defaultRaw, 200, "default raw pair subsidy");
close(
  defaultNormalizedPayout,
  (defaultPool * defaultRaw) / (defaultRaw + defaultHonestDemand),
  "default normalized attack payout"
);
close(
  (100 * defaultNormalizedPayout) / defaultPool,
  (100 * defaultRaw) / (defaultRaw + defaultHonestDemand),
  "default normalized pool share percent"
);
close(defaultM / (defaultM + defaultW), 0.5, "default pair coefficient");
close(defaultPair, 100, "default bounded pair subsidy");
close(defaultGroup, 1000, "default five-colluder bounded subsidy");
close(defaultK * (defaultK - 1) * defaultM, 2000, "default five-colluder ceiling");
close(directMatch(splitPot(10, 100)), 1000, "default ten-sybil funding weight");
close(directSubsidy(splitPot(10, 100)), 900, "default ten-sybil subsidy");

console.log("");
if (failures > 0) {
  console.error(`FAILED: ${failures} of ${checks} checks failed`);
  process.exit(1);
}

console.log(`OK: ${checks} checks passed`);
process.exit(0);
