// Selected-view replay v1. Standalone Node 24+, without packages, repository or network.
// This contract reuses published baseline prices and independently derives wages,
// classic equivalents, default-start CPI alternatives, ranges, ordering and CSV bytes.
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

export const MODEL_VERSION = "selected-data-view-v1";
const MODES = ["catering", "general", "cateringPure"];
const START_YEAR = 1998;
const round = (value, places) => Math.round(value * 10 ** places) / 10 ** places;
export const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
const positive = (value, label) =>
  assert(Number.isFinite(value) && value > 0, `Missing or invalid ${label}`);
const hash = (value, label) =>
  assert(typeof value === "string" && /^[a-f0-9]{64}$/.test(value), `Invalid ${label}`);
const cell = (value) => `"${String(value).replace(/"/g, '""')}"`;

function selectionOf(companion) {
  assert.equal(companion.schema_version, 1, "Unsupported companion schema");
  assert.equal(companion.kind, "gyronomics-selected-data-view", "Unsupported calculation kind");
  assert.equal(companion.model.version, MODEL_VERSION, "Unsupported replay model");
  assert.equal(
    companion.model.baseline_methodology,
    "published-classic-v1",
    "Unsupported baseline methodology",
  );
  assert.equal(companion.model.counterfactual_start_year, START_YEAR, "Unsupported scenario start");
  assert(["el", "en"].includes(companion.language), "Unsupported language");
  const s = companion.selection;
  assert(s && MODES.includes(s.mode), "Unsupported selected mode");
  assert(["classic", "era"].includes(s.unit), "Unsupported selected unit");
  assert(["year", "salary", "pita", "index"].includes(s.sort), "Unsupported selected sort");
  assert(["asc", "desc"].includes(s.dir), "Unsupported selected direction");
  assert(
    Number.isInteger(s.from) && Number.isInteger(s.to) && s.from <= s.to,
    "Invalid selected years",
  );
  assert.deepEqual(
    Object.keys(s).sort(),
    ["dir", "from", "mode", "sort", "to", "unit"],
    "Unexpected selection field",
  );
  return s;
}

function viewUrl(s, lang) {
  const query = new URLSearchParams({
    mode: s.mode,
    unit: s.unit,
    from: String(s.from),
    to: String(s.to),
    sort: s.sort,
    dir: s.dir,
  });
  return `https://gyronomics.gr${lang === "en" ? "/en" : ""}/data?${query}`;
}

export function reconstructDataViewCsv(companion, bundle) {
  const s = selectionOf(companion);
  const lang = companion.language;
  const { dataset, calculations, parameters: p } = bundle;
  assert.equal(bundle.schema_version, 1, "Unsupported bundle schema");
  assert.equal(
    bundle.methodology_version,
    companion.model.baseline_methodology,
    "Baseline methodology mismatch",
  );
  assert.equal(bundle.scope, "baseline-catering-both-product-units", "Unsupported archive scope");
  assert.equal(dataset.cpi_mode, "catering", "Archive must contain the baseline");
  assert.equal(dataset.version, companion.dataset.version, "Dataset version mismatch");
  assert.equal(dataset.updated, companion.dataset.date, "Dataset date mismatch");
  assert.equal(companion.source_url, viewUrl(s, lang), "Selected source URL mismatch");
  assert(
    s.from >= dataset.coverage.from && s.to <= dataset.coverage.to,
    "Selection outside archive coverage",
  );
  assert.equal(
    dataset.rows.length,
    dataset.coverage.to - dataset.coverage.from + 1,
    "Missing baseline years",
  );
  assert.equal(calculations.length, dataset.rows.length, "Missing baseline calculations");
  const calc = new Map(calculations.map((entry) => [entry.year, entry]));
  assert.equal(calc.size, calculations.length, "Duplicate calculation year");
  const sources = new Map(dataset.sources.map((source) => [source.id, source]));
  assert.equal(sources.size, dataset.sources.length, "Duplicate source ID");
  positive(p.drachma_per_euro, "currency conversion");
  positive(p.reference_meat_grams, "reference grams");
  positive(p.meat_cap, "meat cap");
  assert(p.meat_value_share >= 0 && p.meat_value_share < 1, "Invalid meat share");
  assert(p.non_meat_base >= 0 && p.non_meat_base < 1, "Invalid non-meat base");
  assert.equal(p.classic_decimals, 3, "Unsupported classic rounding");

  // The public rounded row is not the compounding seed. The default is a model
  // anchor whose complete precision is retained in the archived calculation.
  const start = calc.get(START_YEAR);
  assert.equal(start?.price.anchor_status, "value", "Missing default scenario anchor");
  const seed = start.price.configured_anchor?.price;
  positive(seed, "unrounded default scenario anchor");
  const paths = { general: seed, cateringPure: seed };
  const years = dataset.rows.map((row, index) => {
    assert.equal(row.year, dataset.coverage.from + index, "Unordered or missing baseline year");
    const c = calc.get(row.year);
    assert(c?.wage && c?.product, `Missing calculation inputs for ${row.year}`);
    const w = c.wage;
    positive(w.original_gross, "gross wage");
    assert(["EUR", "GRD"].includes(w.currency), "Unsupported wage currency");
    assert(
      w.contribution_fraction >= 0 && w.contribution_fraction < 1,
      "Invalid contribution fraction",
    );
    assert(
      Number.isInteger(w.payments) && w.payments > 0 && w.payments <= 14,
      "Invalid payment convention",
    );
    assert.equal(w.income_tax_deducted, false, "Income tax is outside this contract");
    const gross = w.original_gross / (w.currency === "GRD" ? p.drachma_per_euro : 1);
    const salary = round(gross * (1 - w.contribution_fraction) * (w.payments / 12), 2);
    assert.equal(
      salary,
      row.salary_annualized_eur,
      `Archived wage arithmetic mismatch for ${row.year}`,
    );
    positive(c.product.meat_grams, "meat grams");
    assert(c.product.fries_share >= 0 && c.product.fries_share <= 1, "Invalid fries share");
    const rawEquivalence =
      p.meat_value_share * Math.min(c.product.meat_grams / p.reference_meat_grams, p.meat_cap) +
      (1 - p.meat_value_share) * (p.non_meat_base + (1 - p.non_meat_base) * c.product.fries_share);
    const factor = round(1 / round(rawEquivalence, 3), 3);
    positive(row.price_era_eur, "baseline period price");
    positive(row.price_era_min_eur, "baseline lower bound");
    assert(
      row.price_era_min_eur <= row.price_era_eur && row.price_era_eur <= row.price_era_max_eur,
      "Invalid archived price bounds",
    );
    assert.equal(
      round(row.price_era_eur * factor, 3),
      row.price_classic_eur,
      `Archived classic arithmetic mismatch for ${row.year}`,
    );
    const modes = {};
    for (const mode of MODES) {
      const hypothetical = mode !== "catering" && row.year > START_YEAR;
      let periodPrice = row.price_era_eur;
      let minimum = row.price_era_min_eur;
      let maximum = row.price_era_max_eur;
      if (hypothetical) {
        const rate = mode === "general" ? row.cpi_pct : row.catering_cpi_pct;
        assert(Number.isFinite(rate) && rate > -100, `Missing CPI input for ${row.year}`);
        paths[mode] *= 1 + rate / 100;
        periodPrice = round(paths[mode], row.year < 2002 ? 3 : 2);
        // All post-default-start hypothetical years use the existing derived
        // 20% model range, rather than inheriting a later observed anchor range.
        minimum = round(periodPrice * (1 - 0.2), 3);
        maximum = round(periodPrice * (1 + 0.2), 3);
      }
      const price = s.unit === "classic" ? round(periodPrice * factor, 3) : periodPrice;
      const priceMin = minimum * (price / periodPrice);
      const priceMax = maximum * (price / periodPrice);
      modes[mode] = {
        price,
        priceMin,
        priceMax,
        index: Math.round(salary / price),
        low: Math.round(salary / priceMax),
        high: Math.round(salary / priceMin),
        category: hypothetical ? (row.year > 2025 ? "D" : "C") : row.confidence,
        method: hypothetical
          ? `free-compounding-from-${START_YEAR}-${mode === "general" ? "general" : "catering"}-cpi (counterfactual)`
          : row.price_method,
        priceSource: hypothetical ? "cpi" : row.price_source,
      };
    }
    return { year: row.year, salary, modes, wageSource: row.wage_source };
  });
  const chosen = years.filter((row) => row.year >= s.from && row.year <= s.to);
  const sortValue = (row) =>
    s.sort === "index"
      ? row.modes[s.mode].index
      : s.sort === "pita"
        ? row.modes[s.mode].price
        : row[s.sort];
  chosen.sort(
    (a, b) => (s.dir === "asc" ? 1 : -1) * (sortValue(a) - sortValue(b)) || a.year - b.year,
  );
  const others = MODES.filter((mode) => mode !== s.mode);
  const head = [
    "year",
    "net_salary_eur",
    "selected_price_eur",
    "selected_price_min_eur",
    "selected_price_max_eur",
    "selected_index",
    "selected_index_low",
    "selected_index_high",
    ...others.map((mode) => `selected_index_${mode}`),
    "model_category",
    "price_method",
    "price_source_label",
    "price_source_url",
    "salary_source_label",
    "salary_source_url",
    "year_url",
  ];
  const source = (id) => {
    const entry = sources.get(id);
    assert(
      entry && typeof entry[`label_${lang}`] === "string" && typeof entry.url === "string",
      `Missing archived source metadata: ${id}`,
    );
    return entry;
  };
  const body = chosen.map((row) => {
    const v = row.modes[s.mode];
    const ps = source(v.priceSource);
    const ws = source(row.wageSource);
    assert(
      ["A", "B", "C", "D"].includes(v.category) && typeof v.method === "string",
      "Missing archived model metadata",
    );
    return [
      row.year,
      row.salary,
      v.price,
      v.priceMin,
      v.priceMax,
      v.index,
      v.low,
      v.high,
      ...others.map((mode) => row.modes[mode].index),
      v.category,
      v.method,
      ps[`label_${lang}`],
      ps.url,
      ws[`label_${lang}`],
      ws.url,
      `https://gyronomics.gr${lang === "en" ? "/en" : ""}/year/${row.year}`,
    ]
      .map(cell)
      .join(",");
  });
  return (
    "\uFEFF" +
    [
      "# Gyronomics - " + (lang === "el" ? "επιλεγμένη προβολή" : "selected view"),
      `# data_version=${dataset.version} updated=${dataset.updated} cpi_mode=${s.mode} unit=${s.unit} from=${s.from} to=${s.to} sort=${s.sort} dir=${s.dir}`,
      `# selected_price=EUR/${s.unit === "classic" ? "classic-equivalent gyro" : "period gyro"}; selected_index=${s.unit} gyros/month`,
      "# net_salary_eur=annual income after contributions before income tax/12; index bounds are model ranges, not confidence intervals",
      "# " +
        (lang === "el"
          ? "Οι κατηγορίες περιγράφουν το μοντέλο, όχι πιστοποίηση των πηγών. Αναφορές επισκεπτών δεν περιλαμβάνονται."
          : "Categories describe the model, not source certification. Visitor reports are not included."),
      `# ${viewUrl(s, lang)} · CC BY 4.0`,
      head.map(cell).join(","),
      ...body,
      "",
    ].join("\n")
  );
}

export function verifyDataViewFiles({
  companionBytes,
  csvBytes,
  bundleBytes,
  archiveManifestBytes,
  verifierBytes,
}) {
  const c = JSON.parse(Buffer.from(companionBytes).toString("utf8"));
  const s = selectionOf(c);
  hash(c.dataset.archive_sha256, "archive SHA-256");
  hash(c.csv.sha256, "CSV SHA-256");
  hash(c.verifier.sha256, "verifier SHA-256");
  assert.equal(c.csv.encoding, "UTF-8", "Unsupported CSV encoding");
  assert.equal(c.csv.bom, true, "UTF-8 BOM is part of this export contract");
  const expectedFilename = `gyronomics-view-${s.from}-${s.to}-${s.mode}-${s.unit}-${s.sort}-${s.dir}-${c.language}.csv`;
  assert.equal(c.csv.filename, expectedFilename, "CSV filename does not match selection");
  const base = `https://gyronomics.gr/datasets/${c.dataset.archive_sha256}`;
  assert.equal(c.dataset.bundle_url, `${base}/bundle.json`, "Immutable bundle URL mismatch");
  assert.equal(c.dataset.manifest_url, `${base}/manifest.json`, "Immutable manifest URL mismatch");
  assert(
    typeof c.verifier.url === "string" &&
      c.verifier.url.startsWith("https://gyronomics.gr/") &&
      c.verifier.url.endsWith(".mjs"),
    "Invalid public verifier URL",
  );
  assert.equal(
    c.verifier.url,
    `https://gyronomics.gr/research/reproduction/${c.verifier.sha256}/reproduce-data-view-v1.mjs`,
    "Immutable verifier URL mismatch",
  );
  assert.equal(sha256(verifierBytes), c.verifier.sha256, "Verifier checksum mismatch");
  assert.equal(
    sha256(archiveManifestBytes),
    c.dataset.archive_sha256,
    "Archive manifest checksum mismatch",
  );
  const manifest = JSON.parse(Buffer.from(archiveManifestBytes).toString("utf8"));
  assert.equal(manifest.schema_version, 1, "Unsupported archive manifest schema");
  assert.equal(manifest.dataset_version, c.dataset.version, "Archive version mismatch");
  assert.equal(manifest.date, c.dataset.date, "Archive date mismatch");
  assert.equal(
    manifest.methodology_version,
    c.model.baseline_methodology,
    "Archive methodology mismatch",
  );
  assert.equal(sha256(bundleBytes), manifest.files["bundle.json"], "Bundle checksum mismatch");
  assert.equal(sha256(csvBytes), c.csv.sha256, "CSV checksum mismatch");
  const bundle = JSON.parse(Buffer.from(bundleBytes).toString("utf8"));
  const rebuilt = Buffer.from(reconstructDataViewCsv(c, bundle), "utf8");
  assert(
    rebuilt.equals(Buffer.from(csvBytes)),
    "Selected CSV differs from the independently reconstructed bytes",
  );
  return {
    verified: true,
    schema_version: 1,
    model_version: MODEL_VERSION,
    scope: "complete-selected-csv-bytes",
    rows: s.to - s.from + 1,
    csv_sha256: c.csv.sha256,
    archive_sha256: c.dataset.archive_sha256,
    not_verified: [
      "source-authenticity",
      "baseline-price-series-from-original-documents",
      "personal-calculations",
      "non-default-scenario-starts",
    ],
  };
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  try {
    const [companion, csv, bundle, manifest] = process.argv.slice(2);
    assert(
      companion && csv && bundle && manifest && process.argv.length === 6,
      "Usage: node reproduce-data-view-v1.mjs companion.json selected.csv bundle.json manifest.json",
    );
    const result = verifyDataViewFiles({
      companionBytes: readFileSync(companion),
      csvBytes: readFileSync(csv),
      bundleBytes: readFileSync(bundle),
      archiveManifestBytes: readFileSync(manifest),
      verifierBytes: readFileSync(fileURLToPath(import.meta.url)),
    });
    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    console.error(error instanceof Error ? error.message : String(error));
    process.exitCode = 1;
  }
}
