export interface ThinkTagExtractionResult {
  thinking?: string;
  hasThinkTag: boolean;
}

export function extractThinkTagContent(content?: string | null): ThinkTagExtractionResult {
  if (!content) return { thinking: undefined, hasThinkTag: false };

  const matches = [...content.matchAll(/<think>([\s\S]*?)<\/think>/gi)];
  if (!matches.length) return { thinking: undefined, hasThinkTag: false };

  const thinking = matches
    .map(match => match[1]?.trim())
    .filter(Boolean)
    .join('\n\n');

  return {
    thinking: thinking || undefined,
    hasThinkTag: true,
  };
}

function clipText(value: string | undefined | null, max = 2000): string | undefined {
  if (!value) return undefined;
  if (value.length <= max) return value;
  return `${value.slice(0, max)}... [truncated ${value.length - max} chars]`;
}

function sanitizeForLog(value: unknown): unknown {
  if (typeof value === 'string') {
    return clipText(value);
  }
  if (Array.isArray(value)) {
    return value.map(item => sanitizeForLog(item));
  }
  if (value && typeof value === 'object') {
    return Object.fromEntries(
      Object.entries(value as Record<string, unknown>).map(([key, val]) => [key, sanitizeForLog(val)])
    );
  }
  return value;
}

export function logProviderResponse(params: {
  providerId: string;
  providerName: string;
  channelSupplier?: string;
  channelId?: number;
  channelName?: string;
  model: string;
  baseUrl?: string;
  thinkLevel?: string;
  rawResponse: unknown;
  parsed: {
    content?: string;
    thinking?: string;
    thinkSource?: string;
    hasThinkTag?: boolean;
    toolCallCount?: number;
    stopReason?: string;
  };
}): void {
  const payload = {
    providerId: params.providerId,
    providerName: params.providerName,
    channelSupplier: params.channelSupplier,
    channelId: params.channelId,
    channelName: params.channelName,
    model: params.model,
    baseUrl: params.baseUrl,
    thinkLevel: params.thinkLevel,
    parsed: {
      ...params.parsed,
      content: clipText(params.parsed.content),
      thinking: clipText(params.parsed.thinking),
    },
    rawResponse: sanitizeForLog(params.rawResponse),
  };

  console.info('[NetaClaw][LLM_RESPONSE] %s', JSON.stringify(payload));
}
