// Pure future-scenario model v1, shared by the local importer and standalone verifier.
// No network, dynamic code, repository imports or mutable current data are used here.
export const SCENARIO_MODEL_VERSION = "future-scenario-v1";
export const SCENARIO_HORIZON = 2030;
const check = (condition, message) => {
  if (!condition) throw new Error(message);
};
const round = (n, digits = 2) => Math.round(n * 10 ** digits) / 10 ** digits;
const finite = (n, min, max, label) =>
  check(typeof n === "number" && Number.isFinite(n) && n >= min && n <= max, `Invalid ${label}`);
const keys = (value, expected, label) => {
  check(value && typeof value === "object" && !Array.isArray(value), `Invalid ${label}`);
  check(
    Object.keys(value).sort().join("|") === [...expected].sort().join("|"),
    `Unexpected ${label} fields`,
  );
};
export function scenarioCanonicalJson(value) {
  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(scenarioCanonicalJson).join(",") + "]";
  check(value && typeof value === "object", "Invalid JSON value");
  return (
    "{" +
    Object.keys(value)
      .sort()
      .map((key) => JSON.stringify(key) + ":" + scenarioCanonicalJson(value[key]))
      .join(",") +
    "}"
  );
}
const same = (actual, expected, message) =>
  check(scenarioCanonicalJson(actual) === scenarioCanonicalJson(expected), message);
export const SCENARIO_CONVENTIONS = {
  unit: "classic-wrap",
  currency: "EUR",
  payments_per_year: 14,
  months_per_year: 12,
  income_tax_deducted: false,
  pass_through_fraction: 0.5,
  history_from: 2016,
  horizon: SCENARIO_HORIZON,
  monetary_decimals: 2,
  rate_decimals: 3,
  missing_gross: "carry-forward",
  missing_contribution: "carry-forward-then-archived-base",
  scenario_not_forecast: true,
};
export const SCENARIO_VERIFICATION = {
  scope: "selected-future-scenario-rows",
  not_verified: [
    "forecast-accuracy",
    "personal-input-truth",
    "pledge-fulfilment",
    "source-authenticity",
    "income-tax",
  ],
};
export function scenarioArchiveInputs(bundle) {
  check(
    bundle?.schema_version === 1 && bundle.methodology_version === "published-classic-v1",
    "Unsupported archive model",
  );
  check(
    bundle.scope === "baseline-catering-both-product-units" &&
      bundle.dataset?.cpi_mode === "catering",
    "Unsupported archive scope",
  );
  const rows = bundle.dataset.rows;
  const coverage = bundle.dataset.coverage;
  check(
    Array.isArray(rows) &&
      Number.isInteger(coverage?.from) &&
      Number.isInteger(coverage?.to) &&
      rows.length === coverage.to - coverage.from + 1,
    "Invalid archive coverage",
  );
  const calculations = new Map(bundle.calculations.map((row) => [row.year, row]));
  check(calculations.size === rows.length, "Missing archived calculations");
  const values = rows.map((row, index) => {
    check(row.year === coverage.from + index, "Unordered archive rows");
    const contribution = calculations.get(row.year)?.wage?.contribution_fraction;
    finite(contribution, 0, 0.99, "archived contributions");
    finite(row.salary_annualized_eur, 0.01, 1e7, "archived wage");
    finite(row.price_classic_eur, 0.001, 1e5, "archived price");
    finite(row.cpi_pct, -99, 1e4, "archived CPI");
    return {
      year: row.year,
      salary: row.salary_annualized_eur,
      price: row.price_classic_eur,
      cpi: row.cpi_pct,
      contribution,
    };
  });
  const last = values.at(-1);
  check(last.year >= 2016 && last.year < SCENARIO_HORIZON, "Unsupported scenario base year");
  const at = (year) => {
    const row = values.find((r) => r.year === year);
    check(row, "Missing scenario history");
    return row;
  };
  let cpi = 1;
  for (let year = last.year - 9; year <= last.year; year++) cpi *= 1 + at(year).cpi / 100;
  const paymentFactor = (year) => (year <= 1980 ? 1 : year === 1981 ? 13 / 12 : 14 / 12);
  const grossAt = (row) => row.salary / ((1 - row.contribution) * paymentFactor(row.year));
  return {
    values,
    derived: {
      base_year: last.year,
      base_salary: last.salary,
      base_price: last.price,
      base_gross: round(last.salary / ((1 - last.contribution) * (14 / 12))),
      default_contribution_rate: last.contribution,
      price_rates: {
        cpi: round(cpi ** (1 / 10) - 1, 3),
        recent: round((last.price / at(last.year - 10).price) ** (1 / 10) - 1, 3),
        fast: round((last.price / at(last.year - 5).price) ** (1 / 5) - 1, 3),
      },
      wage_history_rate: round((grossAt(last) / grossAt(at(last.year - 10))) ** (1 / 10) - 1, 3),
      pledge_2026_contribution: at(2026).contribution,
    },
  };
}
function presetInputs(id, d) {
  const path = (rate) => {
    let gross = d.base_gross;
    const result = {};
    for (let year = d.base_year + 1; year <= SCENARIO_HORIZON; year++) {
      gross = round(gross * (1 + rate));
      result[year] = gross;
    }
    return result;
  };
  const blend = (a, b, months) => round(a * ((12 - months) / 12) + b * (months / 12));
  if (["frozen", "cpi", "history"].includes(id))
    return {
      gross: path(id === "frozen" ? 0 : id === "cpi" ? d.price_rates.cpi : d.wage_history_rate),
      contribution_rates: {},
      until: SCENARIO_HORIZON,
    };
  if (id === "mitsotakis")
    return {
      gross: { 2027: blend(d.base_gross, 950, 9), 2028: 1000 },
      contribution_rates: {
        2027: round(
          d.pledge_2026_contribution * 0.25 + (d.pledge_2026_contribution - 0.005) * 0.75,
          4,
        ),
        2028: d.pledge_2026_contribution - 0.005,
      },
      until: 2028,
    };
  check(id === "tsipras", "Unknown wage preset");
  return { gross: { 2027: blend(d.base_gross, 1000, 6) }, contribution_rates: {}, until: 2027 };
}
const yearMap = (map, base, until, max, label) => {
  check(map && typeof map === "object" && !Array.isArray(map), `Invalid ${label}`);
  for (const [year, value] of Object.entries(map)) {
    check(
      /^\d{4}$/.test(year) && Number(year) > base && Number(year) <= until,
      `Invalid ${label} year`,
    );
    finite(value, 0, max, label);
  }
};
export function reconstructScenarioResults(receipt, bundle) {
  keys(
    receipt,
    [
      "schema_version",
      "kind",
      "calculation",
      "language",
      "model",
      "source_url",
      "dataset",
      "selection",
      "inputs",
      "derived",
      "assumptions",
      "results",
      "verifier",
      "verification",
      "integrity",
    ],
    "scenario receipt",
  );
  check(
    receipt.schema_version === 1 &&
      receipt.kind === "gyronomics-future-scenario" &&
      receipt.calculation === "future-scenario",
    "Unsupported scenario schema",
  );
  keys(receipt.model, ["version", "baseline_methodology"], "scenario model");
  check(
    receipt.model.version === SCENARIO_MODEL_VERSION &&
      receipt.model.baseline_methodology === "published-classic-v1",
    "Unsupported scenario model",
  );
  check(receipt.language === "el" || receipt.language === "en", "Unsupported language");
  check(
    receipt.source_url === `https://gyronomics.gr${receipt.language === "en" ? "/en" : ""}/senaria`,
    "Scenario source URL mismatch",
  );
  same(receipt.assumptions, SCENARIO_CONVENTIONS, "Unsupported scenario assumptions");
  same(receipt.verification, SCENARIO_VERIFICATION, "Unsupported scenario verification scope");
  const { values, derived: d } = scenarioArchiveInputs(bundle);
  same(receipt.derived, d, "Derived scenario inputs differ from archive");
  check(
    bundle.dataset.version === receipt.dataset.version &&
      bundle.dataset.updated === receipt.dataset.date,
    "Dataset identity mismatch",
  );
  const s = receipt.selection;
  keys(s, ["wage_preset", "price_scenario", "pass_through"], "scenario selection");
  check(
    ["custom", "frozen", "cpi", "history", "mitsotakis", "tsipras"].includes(s.wage_preset),
    "Unknown wage preset",
  );
  check(["cpi", "recent", "fast"].includes(s.price_scenario), "Unknown price scenario");
  check(typeof s.pass_through === "boolean", "Invalid pass-through choice");
  const i = receipt.inputs;
  keys(i, ["gross", "contribution_rates", "until"], "scenario inputs");
  check(
    Number.isInteger(i.until) && i.until > d.base_year && i.until <= SCENARIO_HORIZON,
    "Invalid scenario stopping year",
  );
  yearMap(i.gross, d.base_year, i.until, 5000, "gross wage");
  yearMap(i.contribution_rates, d.base_year, i.until, 0.99, "contribution rate");
  if (s.wage_preset !== "custom")
    same(i, presetInputs(s.wage_preset, d), "Preset assumptions do not match archived inputs");
  const rows = values
    .filter((row) => row.year >= SCENARIO_CONVENTIONS.history_from)
    .map((row) => ({
      year: row.year,
      gross: round(row.salary / ((1 - row.contribution) * (14 / 12))),
      salary: row.salary,
      price: row.price,
      index: Math.round(row.salary / row.price),
      projected: false,
    }));
  let price = d.base_price;
  let previousSalary = d.base_salary;
  let gross = d.base_gross;
  let contribution = d.default_contribution_rate;
  for (let year = d.base_year + 1; year <= i.until; year++) {
    gross = i.gross[year] ?? gross;
    contribution = i.contribution_rates[year] ?? contribution;
    const salary = round(gross * (1 - contribution) * (14 / 12));
    const growth = previousSalary > 0 ? salary / previousSalary - 1 : 0;
    const extra = s.pass_through
      ? Math.max(0, growth) * SCENARIO_CONVENTIONS.pass_through_fraction
      : 0;
    price = round(price * (1 + d.price_rates[s.price_scenario] + extra));
    check(price > 0 && Number.isFinite(price), "Scenario price outside supported range");
    rows.push({ year, gross, salary, price, index: Math.round(salary / price), projected: true });
    previousSalary = salary;
  }
  return { rows };
}
export function assertScenarioResults(receipt, bundle) {
  const results = reconstructScenarioResults(receipt, bundle);
  same(receipt.results, results, "Results differ from independent scenario reconstruction");
  return results;
}

// Standalone Node 24+ entry point. This section is not included in the browser model.
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const scenarioSha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
export function verifyScenarioFiles({
  scenarioBytes,
  bundleBytes,
  archiveManifestBytes,
  verifierBytes,
}) {
  const receipt = JSON.parse(Buffer.from(scenarioBytes).toString("utf8"));
  const { integrity, ...payload } = receipt;
  keys(integrity, ["algorithm", "canonicalization", "sha256"], "integrity");
  check(
    integrity.algorithm === "SHA-256" && integrity.canonicalization === "sorted-json-v1",
    "Unsupported scenario checksum",
  );
  check(
    integrity.sha256 === scenarioSha256(scenarioCanonicalJson(payload)),
    "Scenario checksum mismatch",
  );
  keys(receipt.verifier, ["url", "sha256"], "verifier");
  check(receipt.verifier.sha256 === scenarioSha256(verifierBytes), "Verifier checksum mismatch");
  check(
    receipt.verifier.url ===
      "https://gyronomics.gr/research/reproduction/" +
        receipt.verifier.sha256 +
        "/reproduce-scenario-v1.mjs",
    "Verifier URL mismatch",
  );
  const pin = receipt.dataset;
  keys(pin, ["version", "date", "archive_sha256", "bundle_url", "manifest_url"], "dataset pin");
  check(
    pin.archive_sha256 === scenarioSha256(archiveManifestBytes),
    "Archive manifest checksum mismatch",
  );
  const prefix = "https://gyronomics.gr/datasets/" + pin.archive_sha256;
  check(
    pin.bundle_url === prefix + "/bundle.json" && pin.manifest_url === prefix + "/manifest.json",
    "Archive URL mismatch",
  );
  const manifest = JSON.parse(Buffer.from(archiveManifestBytes).toString("utf8"));
  check(
    manifest.schema_version === 1 &&
      manifest.dataset_version === pin.version &&
      manifest.date === pin.date &&
      manifest.methodology_version === receipt.model.baseline_methodology,
    "Archive metadata mismatch",
  );
  check(manifest.files["bundle.json"] === scenarioSha256(bundleBytes), "Bundle checksum mismatch");
  const result = assertScenarioResults(
    receipt,
    JSON.parse(Buffer.from(bundleBytes).toString("utf8")),
  );
  return {
    verified: true,
    model_version: SCENARIO_MODEL_VERSION,
    scope: SCENARIO_VERIFICATION.scope,
    rows: result.rows.length,
    projected_rows: result.rows.filter((row) => row.projected).length,
    until: receipt.inputs.until,
    archive_sha256: pin.archive_sha256,
    not_verified: SCENARIO_VERIFICATION.not_verified,
  };
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  try {
    const args = process.argv.slice(2);
    check(
      args.length === 3,
      "Usage: node reproduce-scenario-v1.mjs scenario.json bundle.json manifest.json",
    );
    const [scenario, bundle, manifest] = args;
    console.log(
      JSON.stringify(
        verifyScenarioFiles({
          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;
  }
}
