import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS, CAULDRON_FLAVOR_LINES, CAULDRON_EMPTY_FLAVOR, alchemyPotionDefinition } from "../definitions/alchemy.js"; import { ITEM_DEFINITIONS, ItemId, itemDefinition } from "../definitions/items.js"; import { skillLevel, SkillId } from "../definitions/skills.js"; /** Resolve an alchemy ingredient/step item key or id to a player-facing name. */ export function alchemyItemLabel ({ itemId = null, itemKey = null, key = null } = {}) { if (itemId != null) { const def = itemDefinition(itemId); if (def?.displayName) { return def.displayName; } } const lookupKey = itemKey ?? key; if (lookupKey) { const resolvedId = itemIdByKeyMap().get(lookupKey); const def = resolvedId != null ? itemDefinition(resolvedId) : null; if (def?.displayName) { return def.displayName; } return String(lookupKey); } return itemId != null ? String(itemId) : "?"; } /** Serialize a step for hashing / recipe papers. */ export function formatAlchemyStep (step) { if (step.kind === AlchemyStepKind.insert) { if (step.potionKey) { const potion = alchemyPotionDefinition(step.potionKey); return `insert ${potion?.displayName ?? step.potionKey}`; } return `insert ${alchemyItemLabel({ itemId: step.itemId, itemKey: step.itemKey })}`; } return step.kind; } export function hashAlchemySteps (steps) { const text = (steps ?? []).map((step) => { if (step.kind === AlchemyStepKind.insert) { if (step.potionKey) { return `insert:potion:${step.potionKey}`; } return `insert:${step.itemId ?? step.itemKey}`; } return step.kind; }).join("|"); let hash = 2166136261; for (let i = 0; i < text.length; i++) { hash ^= text.charCodeAt(i); hash = Math.imul(hash, 16777619); } return hash >>> 0; } /** Latest cauldron look line from the step hash (or empty copy). */ export function cauldronFlavorText (steps) { if (!(steps?.length > 0)) { return CAULDRON_EMPTY_FLAVOR; } const hash = hashAlchemySteps(steps); return CAULDRON_FLAVOR_LINES[hash % CAULDRON_FLAVOR_LINES.length]; } export function unstablePotionFromSteps (steps) { const hash = hashAlchemySteps(steps); const index = hash % UNSTABLE_POTION_EFFECTS.length; const effect = UNSTABLE_POTION_EFFECTS[index]; return { potionKey: `unstable:${effect.effectKey}`, unstable: true, stepsHash: hash, displayName: effect.displayName, color: effect.color, fillLevel: effect.fillLevel, effect: effect.effect, effectKey: effect.effectKey }; } export function itemIdByKeyMap () { const map = new Map(); for (const def of Object.values(ITEM_DEFINITIONS)) { if (def?.key != null) { map.set(def.key, def.itemId); } } return map; } /** * Resolve ingredient itemIds on potion defs that use item keys (after items are loaded). */ export function resolvePotionIngredientIds (potion, byKey = itemIdByKeyMap()) { const ingredients = (potion.ingredients ?? []).map((row) => { if (row.potionKey) { return { itemId: ItemId.potion, potionKey: row.potionKey, key: row.key ?? row.potionKey, quantity: row.quantity }; } const itemId = row.itemId ?? byKey.get(row.key) ?? null; return { itemId, key: row.key, quantity: row.quantity }; }); const steps = (potion.steps ?? []).map((step) => { if (step.kind !== AlchemyStepKind.insert) { return { ...step }; } if (step.potionKey) { return { kind: AlchemyStepKind.insert, itemId: ItemId.potion, potionKey: step.potionKey, itemKey: step.itemKey ?? "potion" }; } const itemId = step.itemId ?? byKey.get(step.itemKey) ?? null; return { kind: AlchemyStepKind.insert, itemId, itemKey: step.itemKey }; }); return { ...potion, ingredients, steps }; } let cachedResolvedPotions = null; export function resolvedAlchemyPotions () { if (!cachedResolvedPotions) { const byKey = itemIdByKeyMap(); cachedResolvedPotions = Object.values(ALCHEMY_POTION_DEFINITIONS) .map((potion) => resolvePotionIngredientIds(potion, byKey)); } return cachedResolvedPotions; } /** Test helper when potion defs are patched mid-suite. */ export function clearResolvedAlchemyPotionsCache () { cachedResolvedPotions = null; } export function alchemyIngredientNeedKey (row) { if (row?.potionKey) { return `potion:${row.potionKey}`; } return `item:${row?.itemId | 0}`; } export function alchemyStackHaveKey (stack) { if ((stack?.itemId | 0) === ItemId.potion && stack.instance?.potionKey) { return `potion:${stack.instance.potionKey}`; } return `item:${stack?.itemId | 0}`; } /** * Greatest integer batch size for reserved slot quantities vs recipe ingredient ratios. * Returns 0 if ratios do not match (wrong items or non-integer multiple). * Potion ingredients match by potionKey (full bottles still counted as quantity). */ export function alchemyBatchCount (recipeIngredients, reservedStacks) { const need = new Map(); for (const row of recipeIngredients ?? []) { if (row.potionKey) { if (!(row.quantity > 0)) { return 0; } const key = alchemyIngredientNeedKey(row); need.set(key, (need.get(key) ?? 0) + row.quantity); continue; } if (row.itemId == null || row.quantity <= 0) { return 0; } const key = alchemyIngredientNeedKey(row); need.set(key, (need.get(key) ?? 0) + row.quantity); } if (need.size === 0 || need.size > 4) { return 0; } const have = new Map(); for (const stack of reservedStacks ?? []) { if (!stack?.itemId || !(stack.quantity > 0)) { continue; } const key = alchemyStackHaveKey(stack); have.set(key, (have.get(key) ?? 0) + (stack.quantity | 0)); } if (have.size !== need.size) { return 0; } let batch = Infinity; for (const [key, qty] of need) { const got = have.get(key); if (got == null || got % qty !== 0) { return 0; } batch = Math.min(batch, got / qty); } for (const key of have.keys()) { if (!need.has(key)) { return 0; } } return Number.isFinite(batch) && batch > 0 ? batch | 0 : 0; } export function stepsMatchRecipe (takenSteps, recipeSteps) { if (!Array.isArray(takenSteps) || !Array.isArray(recipeSteps)) { return false; } if (takenSteps.length !== recipeSteps.length) { return false; } for (let i = 0; i < recipeSteps.length; i++) { const want = recipeSteps[i]; const got = takenSteps[i]; if (want.kind !== got.kind) { return false; } if (want.kind === AlchemyStepKind.insert) { if ((want.itemId | 0) !== (got.itemId | 0)) { return false; } const wantPotion = want.potionKey ?? null; const gotPotion = got.potionKey ?? null; if (wantPotion || gotPotion) { if (wantPotion !== gotPotion) { return false; } } } } return true; } /** * Evaluate bottling: success potion + batch, or unstable failure. * Underleveled Alchemy on a correct recipe also yields unstable. */ export function evaluateAlchemyBottle ({ skills, brewStacks, takenSteps, potions = resolvedAlchemyPotions() }) { const level = skillLevel(skills, SkillId.alchemy); for (const potion of potions) { const batch = alchemyBatchCount(potion.ingredients, brewStacks); if (batch <= 0) { continue; } if (!stepsMatchRecipe(takenSteps, potion.steps)) { continue; } if (level < (potion.minAlchemyLevel ?? 1)) { return { ok: true, success: false, batch: 1, result: unstablePotionFromSteps(takenSteps), reason: "alchemy-level", recipe: potion }; } return { ok: true, success: true, batch, result: { potionKey: potion.potionKey, unstable: false, displayName: potion.displayName, color: potion.color, fillLevel: potion.fillLevel ?? 4, effect: potion.effect, effectKey: potion.effect?.type ?? potion.potionKey, minAlchemyLevel: potion.minAlchemyLevel ?? 1, outputItemId: potion.outputItemId ?? null, outputQuantity: potion.outputQuantity ?? 1, requiresEmptyBottles: potion.requiresEmptyBottles !== false }, recipe: potion }; } return { ok: true, success: false, batch: 1, result: unstablePotionFromSteps(takenSteps), reason: "no-match" }; } export function recipePaperBody (potion) { const lines = [ `${potion.displayName}`, `Alchemy level required: ${potion.minAlchemyLevel ?? 1}`, "", "Ingredients (ratios):" ]; for (const row of potion.ingredients ?? []) { if (row.potionKey) { const brew = alchemyPotionDefinition(row.potionKey); lines.push(`- ${row.quantity}× ${brew?.displayName ?? row.potionKey} (full bottle)`); continue; } lines.push(`- ${row.quantity}× ${alchemyItemLabel({ itemId: row.itemId, key: row.key })}`); } lines.push("", "Steps:"); for (const step of potion.steps ?? []) { lines.push(`- ${formatAlchemyStep(step)}`); } lines.push("", "Finish by bottling at the cauldron."); return lines.join("\n"); } export function potionItemInstance (result) { return { kind: "potion", potionKey: result.potionKey, unstable: !!result.unstable, displayName: result.displayName, color: result.color, fillLevel: Math.max(1, Math.min(5, result.fillLevel | 0 || 4)), effect: result.effect ?? null, effectKey: result.effectKey ?? result.effect?.type ?? result.potionKey, stepsHash: result.stepsHash ?? null, minAlchemyLevel: result.minAlchemyLevel ?? null }; } /** Resolve a potion instance's gameplay effect (legacy rows may omit `effect`). */ export function resolvePotionEffect (instance) { if (!instance || instance.kind !== "potion") { return null; } if (instance.effect && typeof instance.effect === "object") { return instance.effect; } const potionKey = instance.potionKey; if (!potionKey) { return null; } if (potionKey.startsWith("unstable:")) { const effectKey = potionKey.slice("unstable:".length) || instance.effectKey; const entry = UNSTABLE_POTION_EFFECTS.find((row) => row.effectKey === effectKey); return entry?.effect ?? null; } return alchemyPotionDefinition(potionKey)?.effect ?? null; }