/**
 * Cross-environment phase timing helper.
 *
 * In CF Workers, writes phase durations to `globalThis.__d1Timing__.phases`
 * which the worker middleware reads and emits as Server-Timing headers.
 *
 * In Node.js (Blocklet Server), this is a no-op.
 */

/**
 * Measure the duration of an async operation and record it under a named phase.
 * Usage:
 *   const result = await measurePhase('chain', () => checkTokenBalance(...));
 *
 * Multiple calls to the same phase name accumulate.
 */
export async function measurePhase<T>(name: string, fn: () => Promise<T>): Promise<T> {
  const t0 = typeof performance !== 'undefined' ? performance.now() : Date.now();
  try {
    return await fn();
  } finally {
    const t = (globalThis as any).__d1Timing__;
    if (t && t.phases) {
      const dur = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0;
      t.phases[name] = (t.phases[name] || 0) + dur;
    }
  }
}

/** Record a phase duration directly (for non-Promise paths or manual timing). */
export function recordPhase(name: string, durationMs: number): void {
  const t = (globalThis as any).__d1Timing__;
  if (!t || !t.phases) return;
  t.phases[name] = (t.phases[name] || 0) + durationMs;
}
