// ─── Pact Ritual Pipeline Phase ───────────────────────────────────────────────
// Processes pact ritual signing during the game tick.
// Progress advancement only — completion is delegated to prestigeStore.completePactRitual().

import { getGuardianForFloor } from '../../data/guardian-encounters';
import { HOURS_PER_TICK } from '../../constants';

export interface PactRitualResult {
  /** Null when no ritual is in progress. */
  writes: {
    pactRitualFloor: number | null;
    pactRitualProgress: number;
  } | null;
  /** True when the ritual reached completion threshold this tick. */
  completed: boolean;
}

/**
 * Process pact ritual progression. Advances progress each tick.
 * Returns `completed: true` when enough hours have accumulated;
 * the caller (gameStore tick) must then invoke
 * `usePrestigeStore.getState().completePactRitual(addLog)` to
 * finalise signing — this avoids duplicating the completion logic.
 */
export function processPactRitual(
  pactRitualFloor: number | null,
  pactRitualProgress: number,
  pactAffinityUpgrade: number,
  pactAffinityBonus: number,
): PactRitualResult {
  if (pactRitualFloor === null) return { writes: null, completed: false };

  const guardian = getGuardianForFloor(pactRitualFloor);
  if (!guardian) return { writes: null, completed: false };

  const pactAffinity = Math.min(0.9, pactAffinityUpgrade * 0.1 + pactAffinityBonus);
  const requiredTime = guardian.pactTime * (1 - pactAffinity);

  if (pactRitualProgress + HOURS_PER_TICK >= requiredTime) {
    // Signal completion — state writes happen inside completePactRitual()
    return { writes: null, completed: true };
  }

  return {
    writes: { pactRitualFloor, pactRitualProgress: pactRitualProgress + HOURS_PER_TICK },
    completed: false,
  };
}
