export async function retryWithBackoff<T>(fn: () => Promise<T>, maxRetries: number = 3, baseDelay: number = 1000, context: string = '操作'): Promise<T> {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try { return await fn(); }
    catch (error: any) {
      if (attempt === maxRetries) throw error;
      const delay = baseDelay * Math.pow(2, attempt - 1);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  throw new Error('Unreachable');
}

function countWords(text: string): number { return (text.match(/[\u4e00-\u9fa5]/g) || []).length; }

export function evaluateContentQuality(content: string, expectedWords: number) {
  const issues: string[] = [];
  const wordCount = countWords(content);
  let score = 100;
  const wordRatio = wordCount / expectedWords;
  if (wordRatio < 0.7) score -= 20;
  return { score: Math.max(0, score), issues, wordCount };
}

/**
 * 多模型协同配置
 * 通过环境变量配置不同任务使用的模型
 * 模型必须在 models.json 中已配置
 * 
 * 环境变量:
 * - MODEL_OUTLINE: 大纲生成模型 (默认: MiniMax-M2.7)
 * - MODEL_CONTENT: 内容生成模型 (默认: MiniMax-M2.7)
 * - MODEL_QUALITY: 质量校验模型 (默认: qwen3.5-flash)
 */
export const MODEL_ROLES = {
  outline: process.env.MODEL_OUTLINE || 'MiniMax-M2.7',
  content: process.env.MODEL_CONTENT || 'MiniMax-M2.7',
  quality: process.env.MODEL_QUALITY || 'qwen3.5-flash',
};

export function getModelForRole(role: keyof typeof MODEL_ROLES): string {
  return MODEL_ROLES[role];
}

export function getStylePrompt(style: string): string {
  const styles: any = { academic: '学术严谨', popular: '通俗易懂' };
  return styles[style] || styles.academic;
}

export function postProcessContent(content: string) {
  let processed = content.trim();
  const regex = new RegExp('\\n{4,}', 'g');
  processed = processed.replace(regex, '\n\n\n');
  return { content: processed, issues: [] };
}
