declare global {
  var __performanceMeasurePatched: boolean | undefined
}

function isNegativeTimestampError(error: unknown): boolean {
  if (!(error instanceof Error)) return false
  return error.message.toLowerCase().includes("cannot have a negative time stamp")
}

export function ensurePerformanceMeasurePatched() {
  if (typeof performance === "undefined" || typeof performance.measure !== "function") {
    return
  }

  if (globalThis.__performanceMeasurePatched) {
    return
  }

  const originalMeasure = performance.measure.bind(performance)
  performance.measure = ((name: string, startOrOptions?: string | PerformanceMeasureOptions, endMark?: string) => {
    try {
      return originalMeasure(name, startOrOptions as string | PerformanceMeasureOptions, endMark)
    } catch (error) {
      if (!isNegativeTimestampError(error)) {
        throw error
      }

      if (typeof startOrOptions === "object" && startOrOptions) {
        const safeOptions: PerformanceMeasureOptions = {
          ...startOrOptions,
          start: 0,
        }
        try {
          return originalMeasure(name, safeOptions, endMark)
        } catch {
          return undefined
        }
      } else if (typeof startOrOptions === "string") {
        try {
          return originalMeasure(
            name,
            {
              start: 0,
            },
            endMark
          )
        } catch {
          return undefined
        }
      }

      // swallow invalid marks when start/end names are missing
      return undefined
    }
  }) as typeof performance.measure
  globalThis.__performanceMeasurePatched = true
}

ensurePerformanceMeasurePatched()
