/**
 * Smoke test for tutor review content fingerprint (mirrors generator.js logic).
 * Run: node tools/test_tutor_review_version_fingerprint.js
 */

const TUTOR_REVIEW_FINGERPRINT_FIELDS = [
    "title",
    "stem",
    "lead_in",
    "option_a",
    "option_b",
    "option_c",
    "option_d",
    "option_e",
    "correct_answer",
    "correct_answer_letter",
    "justification",
    "skill",
    "condition_name",
    "presentation"
];

function normalizeFingerprintText(value) {
    return String(value ?? "")
        .replace(/\r\n/g, "\n")
        .trim();
}

function hashStringDjb2(str) {
    let hash = 5381;
    for (let i = 0; i < str.length; i++) {
        hash = ((hash << 5) + hash) ^ str.charCodeAt(i);
    }
    return (hash >>> 0).toString(16);
}

function getQuestionContentFingerprint(q) {
    const parts = TUTOR_REVIEW_FINGERPRINT_FIELDS.map((field) => normalizeFingerprintText(q[field]));
    return hashStringDjb2(parts.join("\u001f"));
}

const base = {
    title: "Test",
    stem: "Stem",
    lead_in: "What is the diagnosis?",
    option_a: "A",
    option_b: "B",
    option_c: "C",
    option_d: "D",
    option_e: "E",
    correct_answer: "A",
    correct_answer_letter: "A",
    justification: "Because",
    skill: "Diagnosis",
    condition_name: "Asthma",
    presentation: "Wheeze"
};

let failed = 0;

function assert(condition, message) {
    if (!condition) {
        console.error("FAIL:", message);
        failed += 1;
    }
}

const h1 = getQuestionContentFingerprint(base);
const h2 = getQuestionContentFingerprint({ ...base });
assert(h1 === h2 && h1.length > 0, "same content yields stable hash");

const changed = { ...base, stem: "New stem" };
assert(getQuestionContentFingerprint(changed) !== h1, "stem change changes hash");

const whitespace = { ...base, stem: "  Stem  \r\n" };
assert(getQuestionContentFingerprint(whitespace) === h1, "whitespace normalisation");

if (failed === 0) {
    console.log("OK: tutor review fingerprint smoke tests passed (" + h1 + ")");
    process.exit(0);
}
process.exit(1);
