/** Max characters for string values in logged step input/output contexts */
const LOG_STRING_TRUNCATE_LIMIT = 200

/**
 * Deep-clone an object, truncating string values that exceed the limit.
 * Keeps the structure intact so the UI timeline can display field names and short previews.
 */
export function truncateForLogging(value: unknown): unknown {
  if (value === null || value === undefined) return value
  if (typeof value === 'string') {
    return value.length > LOG_STRING_TRUNCATE_LIMIT
      ? value.slice(0, LOG_STRING_TRUNCATE_LIMIT) + `… [${value.length} chars]`
      : value
  }
  if (Array.isArray(value)) {
    return value.map(truncateForLogging)
  }
  if (typeof value === 'object') {
    const result: Record<string, unknown> = {}
    for (const [k, v] of Object.entries(value)) {
      result[k] = truncateForLogging(v)
    }
    return result
  }
  return value
}
