/**
 * Message Updaters (Internal)
 *
 * Internal helper functions for updating UIMessage parts.
 * These are used by StreamProcessor to manage the message array.
 */

import { isRedactedThinkingId } from '../../../utilities/reasoning-encrypted-value'
import {
  mergeMetadata,
  tanstackMetadata,
  tanstackOnlyMetadata,
} from '../../../utilities/merge-metadata'
import { parsePartialJSON } from './json-parser'
import type {
  ContentPart,
  StructuredOutputPart,
  ThinkingPart,
  ToolCallPart,
  ToolResultOutcome,
  ToolResultPart,
  UIMessage,
} from '../../../types'
import type { ToolCallState, ToolResultState } from './types'

/**
 * Update or add a text part to a message.
 *
 * If the last part is a text part, update it (continuing the same text segment).
 * Otherwise, create a new text part (starting a new text segment after tool calls).
 */
export function updateTextPart(
  messages: Array<UIMessage>,
  messageId: string,
  content: string,
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    const lastPart = parts.length > 0 ? parts[parts.length - 1] : null

    if (lastPart && lastPart.type === 'text') {
      // Update the last text part (continuing same text segment)
      parts[parts.length - 1] = { type: 'text', content }
    } else {
      // Create new text part (starting new text segment after tool calls/results)
      parts.push({ type: 'text', content })
    }

    return { ...msg, parts }
  })
}

/**
 * Update or add a tool call part to a message.
 */
export function updateToolCallPart(
  messages: Array<UIMessage>,
  messageId: string,
  toolCall: {
    id: string
    name: string
    arguments: string
    state: ToolCallState
    /** Parsed input — set when the arguments are complete. */
    input?: unknown
    metadata?: Record<string, unknown>
  },
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    const existing = parts.find(
      (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCall.id,
    )

    // Carry forward metadata from either the new toolCall or the existing
    // part. Once the adapter has emitted metadata for a tool call (e.g.
    // Gemini's thoughtSignature on TOOL_CALL_START) we must not lose it on
    // subsequent updates that don't re-supply it.
    const metadata = toolCall.metadata ?? existing?.metadata
    // Same for the parsed input: it's supplied once at completion, so
    // subsequent arg-less updates (approval, etc.) must not drop it.
    const input = toolCall.input ?? existing?.input

    const toolCallPart: ToolCallPart = {
      type: 'tool-call',
      id: toolCall.id,
      name: toolCall.name,
      arguments: toolCall.arguments,
      state: toolCall.state,
      // Carry forward approval, output and parsed input from the existing part
      ...(existing?.approval && { approval: { ...existing.approval } }),
      ...(existing?.output !== undefined && { output: existing.output }),
      ...(input !== undefined && { input }),
      ...(metadata !== undefined && { metadata }),
    }

    if (existing) {
      // Update existing tool call
      parts[parts.indexOf(existing)] = toolCallPart
    } else {
      // Add new tool call at the end (preserve natural streaming order)
      parts.push(toolCallPart)
    }

    return { ...msg, parts }
  })
}

/** Drop a control outcome left on metadata after the result itself succeeded. */
export function withoutStaleToolResultOutcome(
  metadata: Record<string, unknown> | undefined,
): Record<string, unknown> | undefined {
  if (metadata == null) return undefined
  const tanstack = tanstackMetadata({ metadata })
  if (tanstack?.toolResultOutcome === undefined) return metadata
  const { toolResultOutcome: _staleOutcome, ...restTanstack } = tanstack
  const nextMetadata = { ...metadata }
  if (Object.keys(restTanstack).length > 0) {
    nextMetadata.tanstack = restTanstack
  } else {
    delete nextMetadata.tanstack
  }
  return Object.keys(nextMetadata).length > 0 ? nextMetadata : undefined
}

/** Drop a text-result mark left on metadata after a non-string replacement. */
export function withoutStaleToolResultKind(
  metadata: Record<string, unknown> | undefined,
): Record<string, unknown> | undefined {
  if (metadata == null) return undefined
  const tanstack = tanstackMetadata({ metadata })
  if (tanstack?.toolResultKind === undefined) return metadata
  const { toolResultKind: _staleKind, ...restTanstack } = tanstack
  const nextMetadata = { ...metadata }
  if (Object.keys(restTanstack).length > 0) {
    nextMetadata.tanstack = restTanstack
  } else {
    delete nextMetadata.tanstack
  }
  return Object.keys(nextMetadata).length > 0 ? nextMetadata : undefined
}

/**
 * Update or add a tool result part to a message.
 */
export function updateToolResultPart(
  messages: Array<UIMessage>,
  messageId: string,
  toolCallId: string,
  content: string | Array<ContentPart>,
  state: ToolResultState,
  error?: string,
  outcome?: ToolResultOutcome,
  metadata?: Record<string, unknown>,
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    const resultPartIndex = parts.findIndex(
      (p): p is ToolResultPart =>
        p.type === 'tool-result' && p.toolCallId === toolCallId,
    )

    const existingResultPart =
      resultPartIndex >= 0
        ? (parts[resultPartIndex] as ToolResultPart)
        : undefined
    // A new result replaces app keys. The reserved tanstack key still merges.
    // An update that omits metadata keeps the existing bag (streaming).
    let mergedMetadata =
      metadata === undefined
        ? existingResultPart?.metadata
        : mergeMetadata(
            tanstackOnlyMetadata(existingResultPart?.metadata),
            metadata,
          )
    if (
      mergedMetadata !== undefined &&
      Object.keys(mergedMetadata).length === 0
    ) {
      mergedMetadata = undefined
    }
    const hasIncomingToolResultOutcome =
      tanstackMetadata({ metadata })?.toolResultOutcome !== undefined

    // A successful retry supersedes a previous denial/cancellation. Do not
    // carry the old control outcome into the new result, or snapshot hydration
    // will incorrectly restore the successful result as an error.
    if (
      state === 'complete' &&
      outcome === undefined &&
      !hasIncomingToolResultOutcome
    ) {
      mergedMetadata = withoutStaleToolResultOutcome(mergedMetadata)
    }

    // A non-string replacement does not re-supply toolResultKind: 'text'.
    // Do not keep a previous text mark, or persist/reload treats object JSON
    // as a string.
    if (tanstackMetadata({ metadata })?.toolResultKind !== 'text') {
      mergedMetadata = withoutStaleToolResultKind(mergedMetadata)
    }

    const toolResultPart: ToolResultPart = {
      type: 'tool-result',
      toolCallId,
      content,
      state,
      ...(outcome !== undefined && { outcome }),
      ...(error && { error }),
      ...(mergedMetadata !== undefined && { metadata: mergedMetadata }),
    }

    if (resultPartIndex >= 0) {
      parts[resultPartIndex] = toolResultPart
    } else {
      parts.push(toolResultPart)
    }

    return { ...msg, parts }
  })
}

/**
 * Update a tool call part with approval request metadata.
 */
export function updateToolCallApproval(
  messages: Array<UIMessage>,
  messageId: string,
  toolCallId: string,
  approvalId: string,
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    const toolCallPart = parts.find(
      (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,
    )

    if (toolCallPart) {
      const index = parts.indexOf(toolCallPart)
      parts[index] = {
        ...toolCallPart,
        state: 'approval-requested',
        approval: {
          id: approvalId,
          needsApproval: true,
        },
      }
    }

    return { ...msg, parts }
  })
}

/**
 * Update a tool call part's state (e.g., to "input-complete").
 */
export function updateToolCallState(
  messages: Array<UIMessage>,
  messageId: string,
  toolCallId: string,
  state: ToolCallState,
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    const toolCallPart = parts.find(
      (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,
    )

    if (toolCallPart) {
      const index = parts.indexOf(toolCallPart)
      parts[index] = { ...toolCallPart, state }
    }

    return { ...msg, parts }
  })
}

/**
 * Update a tool call part with output.
 * Searches all messages to find the tool call by ID.
 * `resultMetadata` holds only the app keys of the result metadata.
 */
export function updateToolCallWithOutput(
  messages: Array<UIMessage>,
  toolCallId: string,
  output: any,
  state?: ToolCallState,
  errorText?: string,
  resultMetadata?: Record<string, unknown>,
): Array<UIMessage> {
  return messages.map((msg) => {
    const parts = [...msg.parts]
    const toolCallPart = parts.find(
      (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,
    )

    if (toolCallPart) {
      const index = parts.indexOf(toolCallPart)
      // A new result replaces the old result metadata, also when it has none.
      const { resultMetadata: _previous, ...rest } = toolCallPart
      parts[index] = {
        ...rest,
        output: errorText ? { error: errorText } : output,
        state: state ?? (errorText ? 'error' : 'complete'),
        ...(resultMetadata !== undefined && { resultMetadata }),
      }
    }

    return { ...msg, parts }
  })
}

/**
 * Update a tool call part with approval response.
 * Searches all messages to find the tool call by approval ID.
 */
export function updateToolCallApprovalResponse(
  messages: Array<UIMessage>,
  approvalId: string,
  approved: boolean,
): Array<UIMessage> {
  return messages.map((msg) => {
    const parts = [...msg.parts]
    const toolCallPart = parts.find(
      (p): p is ToolCallPart =>
        p.type === 'tool-call' && p.approval?.id === approvalId,
    )

    if (toolCallPart && toolCallPart.approval) {
      const index = parts.indexOf(toolCallPart)
      parts[index] = {
        ...toolCallPart,
        approval: { ...toolCallPart.approval, approved },
        state: 'approval-responded',
      }
    }

    return { ...msg, parts }
  })
}

/**
 * Append a delta to the structured-output part on `messageId`, or create one
 * if absent. Progressive parse of the accumulated buffer fills `partial`.
 *
 * Callers must only invoke this while the part is still in flight — the
 * helper unconditionally writes `status: 'streaming'`, so feeding it a delta
 * after a `complete`/`error` terminal would regress the part. In practice the
 * processor gates calls via `structuredMessageIds`, which is dropped on
 * terminal events.
 *
 * If the progressive parse returns null/undefined (the buffer is not yet a
 * parseable JSON prefix), the previously-good `partial` is preserved so the
 * UI doesn't flicker back to empty for a single render.
 */
export function appendStructuredOutputDelta(
  messages: Array<UIMessage>,
  messageId: string,
  delta: string,
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    const existingIndex = parts.findIndex(
      (p): p is StructuredOutputPart => p.type === 'structured-output',
    )
    const existing =
      existingIndex >= 0 ? (parts[existingIndex] as StructuredOutputPart) : null

    const nextRaw = (existing?.raw ?? '') + delta
    const progressive = parsePartialJSON(nextRaw)
    const nextPartial =
      progressive !== undefined && progressive !== null
        ? progressive
        : existing?.partial

    const nextPart: StructuredOutputPart = {
      type: 'structured-output',
      status: 'streaming',
      raw: nextRaw,
      ...(nextPartial !== undefined ? { partial: nextPartial } : {}),
      ...(existing?.reasoning !== undefined
        ? { reasoning: existing.reasoning }
        : {}),
    }

    if (existingIndex >= 0) {
      parts[existingIndex] = nextPart
    } else {
      parts.push(nextPart)
    }

    return { ...msg, parts }
  })
}

/**
 * Snap the structured-output part on `messageId` to `complete` with the
 * validated `data`. Picks the freshest available `raw` so the wire
 * round-trip stays internally consistent:
 *
 *   1. Caller-supplied `raw` (the original streamed bytes from the model).
 *   2. The existing part's `raw` (deltas accumulated before this terminal).
 *   3. `JSON.stringify(data)` as a defensive fallback for terminal-only
 *      completes that never shipped raw — keeps the part self-consistent
 *      so downstream consumers never see a complete part with empty raw.
 */
export function completeStructuredOutputPart(
  messages: Array<UIMessage>,
  messageId: string,
  data: unknown,
  raw: string,
  reasoning?: string,
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    const existingIndex = parts.findIndex(
      (p): p is StructuredOutputPart => p.type === 'structured-output',
    )

    const existingRaw =
      existingIndex >= 0
        ? (parts[existingIndex] as StructuredOutputPart).raw
        : ''
    let resolvedRaw = raw || existingRaw
    if (resolvedRaw === '' && data !== undefined) {
      try {
        resolvedRaw = JSON.stringify(data)
      } catch {
        // Unserializable (circular, BigInt, throwing toJSON). Leave raw
        // empty. Both downstream paths handle this: `ag-ui-wire.ts`
        // `collectText` skips complete parts with empty raw entirely, and
        // `uiMessageToModelMessages` falls back to a defensive
        // `safeJsonStringify(data)` which itself returns `''` for the same
        // unserializable inputs — so the turn is silently dropped from the
        // next request rather than shipping garbage or crashing the stream.
      }
    }

    const nextPart: StructuredOutputPart = {
      type: 'structured-output',
      status: 'complete',
      data,
      partial: data,
      raw: resolvedRaw,
      ...(reasoning !== undefined ? { reasoning } : {}),
    }

    if (existingIndex >= 0) {
      parts[existingIndex] = nextPart
    } else {
      parts.push(nextPart)
    }

    return { ...msg, parts }
  })
}

/**
 * Mark the structured-output part on `messageId` as errored. If no part
 * exists yet — RUN_ERROR fired after `structured-output.start` but before
 * any delta — create an empty errored placeholder so consumers have
 * something renderable. Existing complete parts are left alone (an error
 * after a successful complete should not retroactively un-complete it).
 */
export function errorStructuredOutputPart(
  messages: Array<UIMessage>,
  messageId: string,
  errorMessage: string,
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    const existingIndex = parts.findIndex(
      (p): p is StructuredOutputPart => p.type === 'structured-output',
    )

    if (existingIndex < 0) {
      parts.push({
        type: 'structured-output',
        status: 'error',
        raw: '',
        errorMessage,
      })
      return { ...msg, parts }
    }

    const existing = parts[existingIndex] as StructuredOutputPart
    if (existing.status === 'complete') {
      return msg
    }
    parts[existingIndex] = {
      ...existing,
      status: 'error',
      errorMessage,
    }
    return { ...msg, parts }
  })
}

// The reasoning step that wrote each live thinking part. The step id is the
// processor's key; it is not on the part, so stored and wire forms have no
// field for it. A part from storage or the wire has no entry.
const thinkingStepOf = new WeakMap<object, string>()

/**
 * Carry the live reasoning-step key from `source` onto `clone`.
 * Freeze/thaw and other shallow copies drop the WeakMap entry, so a later
 * step would otherwise treat the copy as hydrated and overwrite step 1.
 */
export function copyThinkingStepOf(source: object, clone: object): void {
  const stepId = thinkingStepOf.get(source)
  if (stepId !== undefined) thinkingStepOf.set(clone, stepId)
}

/**
 * Update or add a thinking part to a message, keyed by stepId.
 * Each distinct stepId produces its own ThinkingPart.
 */
export function updateThinkingPart(
  messages: Array<UIMessage>,
  messageId: string,
  stepId: string,
  content: string,
  signature?: string,
): Array<UIMessage> {
  return messages.map((msg) => {
    if (msg.id !== messageId) {
      return msg
    }

    const parts = [...msg.parts]
    let thinkingPartIndex = parts.findIndex(
      (p) => p.type === 'thinking' && thinkingStepOf.get(p) === stepId,
    )

    // A hydrated message's thinking parts belong to no step. When a run is
    // rejoined mid-stream the replayed reasoning matches nothing and would be
    // appended -- leaving a second thinking part sitting after the answer
    // text. Adopt the first thinking part with no step instead, so the replay
    // lands on the part it belongs to. Live streaming always records a step,
    // so the only parts this can match are hydrated ones.
    let adopted: ThinkingPart | undefined
    if (thinkingPartIndex < 0) {
      thinkingPartIndex = parts.findIndex(
        (p) => p.type === 'thinking' && !thinkingStepOf.has(p),
      )
      const candidate = parts[thinkingPartIndex]
      if (candidate?.type === 'thinking') adopted = candidate
    }

    // Keep the signature the hydrated part already had when this update does
    // not carry one; losing it would strip the provider's encrypted reasoning
    // from a message that is about to be sent back.
    const nextSignature = signature ?? adopted?.signature
    // A hydrated part has no stepId to carry the redacted marker, so it keeps
    // its own flag.
    const redacted = isRedactedThinkingId(stepId) || adopted?.redacted === true

    const thinkingPart: ThinkingPart = {
      type: 'thinking',
      content,
      ...(nextSignature && { signature: nextSignature }),
      ...(redacted && { redacted: true }),
    }
    thinkingStepOf.set(thinkingPart, stepId)

    if (thinkingPartIndex >= 0) {
      // Update existing thinking part for this step
      parts[thinkingPartIndex] = thinkingPart
    } else {
      // Add new thinking part at the end (preserve natural streaming order)
      parts.push(thinkingPart)
    }

    return { ...msg, parts }
  })
}
