import test from "node:test";
import assert from "node:assert/strict";
import { deriveFields } from "../server/prefill.js";
import { computeLedger } from "../shared/ledger.js";

const base = {
	coffeeName: "Test Coffee",
	cultivar: null,
	cultivarGroup: null,
	origin: "Colombia",
	producer: null,
	process: "washed",
	roastLevel: "light",
	tastingNotes: [],
	altitudeMasl: null,
	screen: null,
	moisturePct: null,
	isBlend: false,
	blendComponents: [],
};

test("known cultivar uses the cultivar table row", () => {
	const { fields, provenance } = deriveFields({ ...base, cultivar: "Gesha" });
	assert.equal(fields["1.1"], "Gesha");
	assert.equal(fields["1.2"], "ethiopian");
	assert.equal(fields["1.4"], "7:30");
	assert.equal(provenance["1.4"], "cultivar-table");
});

test("unknown cultivar with a classified group falls back to the group anchor so the ledger computes", () => {
	const { fields, provenance, warnings } = deriveFields({
		...base,
		cultivar: "Wush Wush",
		cultivarGroup: "ethiopian",
	});
	assert.equal(fields["1.1"], "Wush Wush");
	assert.equal(fields["1.2"], "ethiopian");
	assert.equal(fields["1.4"], "7:25"); // midpoint of the ethiopian group anchor 7:20-7:30
	assert.equal(provenance["1.4"], "group-table");
	assert.match(warnings.join(" "), /group anchor/);
	// The whole point: first crack is now computable
	const ledger = computeLedger({ fields });
	assert.equal(ledger.A !== null, true);
});

test("unknown cultivar in the unparseable hybrid group still degrades gracefully", () => {
	const { fields, warnings } = deriveFields({
		...base,
		cultivar: "Mystery F1",
		cultivarGroup: "hybrid", // group anchor is "follows parent" — not a number
	});
	assert.equal(fields["1.1"], "Mystery F1");
	assert.equal(fields["1.4"], undefined);
	assert.match(warnings.join(" "), /pick the nearest group by hand/);
});

test("unknown cultivar with no group keeps the old blank-fields warning", () => {
	const { fields, warnings } = deriveFields({ ...base, cultivar: "Zebra SP" });
	assert.equal(fields["1.4"], undefined);
	assert.match(warnings.join(" "), /pick the nearest group by hand/);
});
