import { definePlugin } from '@cherrystudio/ai-core'
import { loggerService } from '@logger'
import type { LanguageModelMiddleware } from 'ai'

const logger = loggerService.withContext('skipGeminiThoughtSignaturePlugin')

/**
 * skip Gemini Thought Signature Middleware
 *
 * Handles:
 * - Tool-call parts need thought_signature for OpenAI-compatible API
 *   -> Add providerOptions.openaiCompatible.extra_content.google.thought_signature
 *
 * Note: Thought signature for text/reasoning parts is now handled in messageConverter.
 *
 * @returns LanguageModelMiddleware
 */
function createSkipGeminiThoughtSignatureMiddleware(): LanguageModelMiddleware {
  const MAGIC_STRING = 'skip_thought_signature_validator'
  return {
    specificationVersion: 'v3',

    transformParams: async ({ params }) => {
      const transformedParams = { ...params }
      logger.debug('transformedParams', transformedParams)
      // Process messages in prompt
      if (transformedParams.prompt && Array.isArray(transformedParams.prompt)) {
        transformedParams.prompt = transformedParams.prompt.map((message) => {
          // Tool-call parts only ever live in assistant messages.
          if (message.role !== 'assistant') {
            return message
          }
          // Note: text part and reasoning part do not require thought signature validation
          // They are handled by messageConverter now.
          // Map to NEW part objects instead of mutating caller-owned parts in place.
          return {
            ...message,
            content: message.content.map((part) => {
              // Case: OpenAI-compatible path - add extra_content for tool-call parts
              // All tool-calls need the signature for Gemini OpenAI-compatible API
              if (part.type !== 'tool-call') {
                return part
              }
              // Google OpenAI-compatible API expects extra_content.google.thought_signature
              // See: https://ai.google.dev/gemini-api/docs/thought-signatures#openai
              return {
                ...part,
                providerOptions: {
                  ...part.providerOptions,
                  openaiCompatible: {
                    ...part.providerOptions?.openaiCompatible,
                    extra_content: {
                      google: {
                        thought_signature: MAGIC_STRING
                      }
                    }
                  }
                }
              }
            })
          }
        })
      }

      return transformedParams
    }
  }
}

const createSkipGeminiThoughtSignaturePlugin = () =>
  definePlugin({
    name: 'skip-gemini-thought-signature',
    enforce: 'pre',

    configureContext: (context) => {
      context.middlewares = context.middlewares || []
      context.middlewares.push(createSkipGeminiThoughtSignatureMiddleware())
    }
  })

import { isGemini3Model } from '@shared/utils/model'

import type { RequestFeature } from '../feature'

/** Inject thought_signature on tool calls for Gemini 3 via OpenAI-compat API. */
export const skipGeminiThoughtSignatureFeature: RequestFeature = {
  name: 'skip-gemini-thought-signature',
  applies: (scope) => isGemini3Model(scope.model),
  contributeModelAdapters: () => [createSkipGeminiThoughtSignaturePlugin()]
}
