const fs = require('fs');

const file = 'src/services/llm/index.ts';
let content = fs.readFileSync(file, 'utf8');

// 在 callLLMWithMessages 函数中添加日志
const old = `export async function callLLMWithMessages(
  messages: ChatMessage[],
  modelId?: string
): Promise<string> {
  const id = modelId || config.models.textGeneration.defaultModel;
  try {
    const llm = getLLM(id);
    const baseMessages = toBaseMessages(messages);
    const response = await llm.invoke(baseMessages as any);
    return response.content as string;`;

const new_ = `export async function callLLMWithMessages(
  messages: ChatMessage[],
  modelId?: string
): Promise<string> {
  const id = modelId || config.models.textGeneration.defaultModel;
  
  // 记录请求日志
  console.log('[AI请求] ===== 开始 =====');
  console.log('[AI请求] 模型:', id);
  console.log('[AI请求] 消息数:', messages.length);
  const systemMsg = messages.find(m => m.role === 'system');
  if (systemMsg) {
    console.log('[AI请求] System提示词 (前200字):', systemMsg.content.substring(0, 200));
  }
  const userMsg = messages.find(m => m.role === 'user');
  if (userMsg) {
    console.log('[AI请求] User消息 (前200字):', userMsg.content.substring(0, 200));
  }
  
  try {
    const llm = getLLM(id);
    const baseMessages = toBaseMessages(messages);
    const response = await llm.invoke(baseMessages as any);
    
    // 记录响应日志
    const responseContent = response.content as string;
    console.log('[AI响应] ===== 开始 =====');
    console.log('[AI响应] 完整内容 (前1000字):', responseContent.substring(0, 1000));
    if (responseContent.length > 1000) {
      console.log('[AI响应] ... (总长度:', responseContent.length, '字)');
    }
    console.log('[AI响应] ===== 结束 =====');
    
    return responseContent;`;

content = content.replace(old, new_);

fs.writeFileSync(file, content, 'utf8');
console.log('✅ AI 交互日志已添加');
