// Trusted browser replay of salary receipts. Independent of the application's series engine.
export const MODEL_VERSION = "salary-calculation-v1";
const check = (condition, message) => {
  if (!condition) throw new Error(message);
};
const equal = (a, b, message) => check(canonicalJson(a) === canonicalJson(b), message);
const round = (value, places) => Math.round(value * 10 ** places) / 10 ** places;
const positive = (value, label) =>
  check(typeof value === "number" && Number.isFinite(value) && value > 0, `Invalid ${label}`);
const exactKeys = (value, keys, label) => {
  check(value && typeof value === "object" && !Array.isArray(value), `Invalid ${label}`);
  equal(Object.keys(value).sort(), [...keys].sort(), `Unexpected ${label} fields`);
};
export function canonicalJson(value, depth = 0) {
  check(depth <= 30, "JSON nesting exceeds limit");
  if (value === null || typeof value === "string" || typeof value === "boolean")
    return JSON.stringify(value);
  if (typeof value === "number") {
    check(Number.isFinite(value), "Non-finite JSON number");
    return JSON.stringify(value);
  }
  if (Array.isArray(value))
    return "[" + value.map((item) => canonicalJson(item, depth + 1)).join(",") + "]";
  check(value && typeof value === "object", "Invalid canonical JSON value");
  return (
    "{" +
    Object.keys(value)
      .sort()
      .map((key) => JSON.stringify(key) + ":" + canonicalJson(value[key], depth + 1))
      .join(",") +
    "}"
  );
}
export async function sha256(bytes) {
  const input = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
  return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", input)), (byte) =>
    byte.toString(16).padStart(2, "0"),
  ).join("");
}
export function validateSalaryReceipt(c) {
  const pending = [[c, 0]];
  while (pending.length) {
    const [value, depth] = pending.pop();
    check(depth <= 16, "JSON nesting exceeds limit");
    if (value && typeof value === "object")
      for (const child of Object.values(value)) pending.push([child, depth + 1]);
  }
  exactKeys(
    c,
    [
      "schema_version",
      "kind",
      "language",
      "model",
      "inputs",
      "results",
      "source_url",
      "dataset",
      "verifier",
      "verification",
      "integrity",
    ],
    "receipt",
  );
  equal(c.schema_version, 1, "Unsupported salary schema");
  equal(c.kind, "gyronomics-salary-calculation", "Unsupported calculation kind");
  check(["el", "en"].includes(c.language), "Unsupported language");
  equal(
    c.model,
    {
      version: MODEL_VERSION,
      baseline_methodology: "published-classic-v1",
      counterfactual_start_year: 1998,
      unit: "classic",
      twin_tolerance: 0.05,
      twin_tie_break: "earliest-year",
      factor: "payments-divided-by-12",
      income_tax_deducted: false,
    },
    "Unsupported salary model",
  );
  exactKeys(c.inputs, ["salary", "basis", "mode"], "salary input");
  const i = c.inputs;
  positive(i.salary, "salary");
  check(
    Number.isSafeInteger(Math.round(i.salary * 100)) && round(i.salary, 2) === i.salary,
    "Salary must have cent precision",
  );
  check(["annual", "contract"].includes(i.basis), "Invalid salary basis");
  check(["catering", "general", "cateringPure"].includes(i.mode), "Unsupported scenario mode");
  exactKeys(
    c.dataset,
    ["version", "date", "archive_sha256", "bundle_url", "manifest_url"],
    "dataset pin",
  );
  check(
    typeof c.dataset.version === "string" &&
      typeof c.dataset.date === "string" &&
      /^[a-f0-9]{64}$/.test(c.dataset.archive_sha256),
    "Invalid dataset identity",
  );
  equal(
    c.dataset.bundle_url,
    `https://gyronomics.gr/datasets/${c.dataset.archive_sha256}/bundle.json`,
    "Immutable bundle URL mismatch",
  );
  equal(
    c.dataset.manifest_url,
    `https://gyronomics.gr/datasets/${c.dataset.archive_sha256}/manifest.json`,
    "Immutable manifest URL mismatch",
  );
  exactKeys(c.verifier, ["url", "sha256"], "verifier pin");
  check(/^[a-f0-9]{64}$/.test(c.verifier.sha256), "Invalid verifier identity");
  equal(
    c.verifier.url,
    `https://gyronomics.gr/research/reproduction/${c.verifier.sha256}/reproduce-salary-v1.mjs`,
    "Immutable verifier URL mismatch",
  );
  const query = new URLSearchParams({ salary: String(i.salary), basis: i.basis });
  // The live calculator currently uses catering. Alternate model receipts identify
  // the selected model in inputs; this link is an entry point, not an archive.
  equal(
    c.source_url,
    `https://gyronomics.gr${c.language === "en" ? "/en" : ""}/calculator?${query}#salary-comparison`,
    "Salary source URL mismatch",
  );
  equal(
    c.verification,
    {
      scope: "salary-and-complete-historical-comparison",
      not_verified: [
        "personal-input-truth",
        "source-authenticity",
        "baseline-price-series-from-original-documents",
        "income-tax",
      ],
    },
    "Verification scope mismatch",
  );
  exactKeys(c.integrity, ["algorithm", "canonicalization", "sha256"], "integrity");
  equal(c.integrity.algorithm, "SHA-256", "Unsupported checksum algorithm");
  equal(c.integrity.canonicalization, "sorted-json-v1", "Unsupported canonicalization");
  check(/^[a-f0-9]{64}$/.test(c.integrity.sha256), "Invalid scenario checksum");
  return c;
}
export function reconstructSalaryResults(c, bundle) {
  validateSalaryReceipt(c);
  equal(bundle.schema_version, 1, "Unsupported bundle schema");
  equal(bundle.methodology_version, c.model.baseline_methodology, "Baseline methodology mismatch");
  equal(bundle.scope, "baseline-catering-both-product-units", "Unsupported archive scope");
  const { dataset, calculations, parameters: p } = bundle;
  equal(dataset.cpi_mode, "catering", "Archive must contain baseline");
  equal(dataset.version, c.dataset.version, "Dataset version mismatch");
  equal(dataset.updated, c.dataset.date, "Dataset date mismatch");
  check(
    Number.isInteger(dataset.coverage.from) &&
      Number.isInteger(dataset.coverage.to) &&
      dataset.coverage.to >= dataset.coverage.from,
    "Invalid archive coverage",
  );
  equal(
    dataset.rows.length,
    dataset.coverage.to - dataset.coverage.from + 1,
    "Missing archive rows",
  );
  equal(calculations.length, dataset.rows.length, "Missing archive calculations");
  const calc = new Map(calculations.map((row) => [row.year, row]));
  equal(calc.size, calculations.length, "Duplicate calculation year");
  positive(p.drachma_per_euro, "currency conversion");
  positive(p.reference_meat_grams, "reference grams");
  positive(p.meat_cap, "meat cap");
  check(p.meat_value_share >= 0 && p.meat_value_share < 1, "Invalid meat share");
  check(p.non_meat_base >= 0 && p.non_meat_base < 1, "Invalid non-meat base");
  equal(p.classic_decimals, 3, "Unsupported classic rounding");
  const mode = c.inputs.mode;
  let path;
  if (mode !== "catering") {
    const anchor = calc.get(1998);
    equal(anchor?.price.anchor_status, "value", "Missing scenario anchor");
    path = anchor.price.configured_anchor?.price;
    positive(path, "unrounded scenario anchor");
  }
  let payments;
  const rows = dataset.rows.map((row, index) => {
    equal(row.year, dataset.coverage.from + index, "Unordered or missing year");
    const detail = calc.get(row.year);
    check(detail?.wage && detail?.product, "Missing archived inputs");
    const w = detail.wage;
    positive(w.original_gross, "gross wage");
    check(["EUR", "GRD"].includes(w.currency), "Invalid wage currency");
    check(
      w.contribution_fraction >= 0 && w.contribution_fraction < 1,
      "Invalid contribution fraction",
    );
    check(
      Number.isInteger(w.payments) && w.payments > 0 && w.payments <= 14,
      "Invalid payment count",
    );
    equal(w.income_tax_deducted, false, "Income tax outside model");
    const salary = round(
      (w.original_gross / (w.currency === "GRD" ? p.drachma_per_euro : 1)) *
        (1 - w.contribution_fraction) *
        (w.payments / 12),
      2,
    );
    equal(salary, row.salary_annualized_eur, "Archived wage arithmetic mismatch");
    equal(w.payments, row.salary_payments, "Archived payment count mismatch");
    payments = w.payments;
    positive(detail.product.meat_grams, "meat grams");
    check(
      detail.product.fries_share >= 0 && detail.product.fries_share <= 1,
      "Invalid fries share",
    );
    const equivalence =
      p.meat_value_share *
        Math.min(detail.product.meat_grams / p.reference_meat_grams, p.meat_cap) +
      (1 - p.meat_value_share) *
        (p.non_meat_base + (1 - p.non_meat_base) * detail.product.fries_share);
    const factor = round(1 / round(equivalence, 3), 3);
    positive(row.price_era_eur, "period price");
    equal(
      round(row.price_era_eur * factor, 3),
      row.price_classic_eur,
      "Archived classic price mismatch",
    );
    let periodPrice = row.price_era_eur;
    if (mode !== "catering" && row.year > 1998) {
      const rate = mode === "general" ? row.cpi_pct : row.catering_cpi_pct;
      check(
        typeof rate === "number" && Number.isFinite(rate) && rate > -100,
        "Invalid scenario CPI",
      );
      path *= 1 + rate / 100;
      periodPrice = round(path, row.year < 2002 ? 3 : 2);
    }
    const price = round(periodPrice * factor, 3);
    positive(price, "selected classic price");
    return { year: row.year, price, salary, index: Math.round(salary / price) };
  });
  const last = rows.at(-1);
  const comparable =
    c.inputs.basis === "contract" ? c.inputs.salary * (payments / 12) : c.inputs.salary;
  const index = Math.round(comparable / last.price);
  const highest = rows.reduce((a, b) => (b.index > a.index ? b : a));
  const lowest = rows.reduce((a, b) => (b.index < a.index ? b : a));
  let twin, kind;
  if (index > highest.index) {
    twin = highest;
    kind = "above";
  } else if (index < lowest.index) {
    twin = lowest;
    kind = "below";
  } else {
    twin = rows.reduce((a, b) => (Math.abs(b.index - index) < Math.abs(a.index - index) ? b : a));
    kind = Math.abs(twin.index - index) <= index * 0.05 ? "same" : "near";
  }
  return {
    year: last.year,
    payments,
    price: last.price,
    minimumIndex: last.index,
    minimumSalary: last.salary,
    comparable,
    index,
    diff: index - last.index,
    twin: { year: twin.year, index: twin.index, kind },
    rows,
  };
}
export async function verifySalaryFiles({
  scenarioBytes,
  bundleBytes,
  archiveManifestBytes,
  verifierBytes,
}) {
  check(scenarioBytes.byteLength <= 512 * 1024, "Scenario file exceeds size limit");
  const c = validateSalaryReceipt(JSON.parse(new TextDecoder().decode(scenarioBytes)));
  const { integrity, ...payload } = c;
  equal(await sha256(canonicalJson(payload)), integrity.sha256, "Scenario checksum mismatch");
  if (verifierBytes)
    equal(await sha256(verifierBytes), c.verifier.sha256, "Verifier checksum mismatch");
  equal(
    await sha256(archiveManifestBytes),
    c.dataset.archive_sha256,
    "Archive manifest checksum mismatch",
  );
  const manifest = JSON.parse(new TextDecoder().decode(archiveManifestBytes));
  equal(manifest.schema_version, 1, "Unsupported manifest schema");
  equal(manifest.dataset_version, c.dataset.version, "Archive version mismatch");
  equal(manifest.date, c.dataset.date, "Archive date mismatch");
  equal(manifest.methodology_version, c.model.baseline_methodology, "Archive methodology mismatch");
  equal(await sha256(bundleBytes), manifest.files["bundle.json"], "Bundle checksum mismatch");
  const result = reconstructSalaryResults(c, JSON.parse(new TextDecoder().decode(bundleBytes)));
  equal(c.results, result, "Results differ from independent reconstruction");
  return {
    verified: true,
    schema_version: 1,
    model_version: MODEL_VERSION,
    scope: c.verification.scope,
    rows: result.rows.length,
    archive_sha256: c.dataset.archive_sha256,
  };
}

// Standalone CLI uses only local files; no repository or network.
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  try {
    const [scenario, bundle, manifest] = process.argv.slice(2);
    if (process.argv.length !== 5)
      throw new Error(
        "Usage: node reproduce-salary-v1.mjs scenario.json bundle.json manifest.json",
      );
    console.log(
      JSON.stringify(
        await verifySalaryFiles({
          scenarioBytes: readFileSync(scenario),
          bundleBytes: readFileSync(bundle),
          archiveManifestBytes: readFileSync(manifest),
          verifierBytes: readFileSync(fileURLToPath(import.meta.url)),
        }),
        null,
        2,
      ),
    );
  } catch (error) {
    console.error(error instanceof Error ? error.message : String(error));
    process.exitCode = 1;
  }
}
