import { Novel } from '../types';

export class NovelSettingManager {
  /**
   * 生成小说设置文件内容（优化版）
   */
  static generateSettingContent(title: string, settings: any): string {
    let content = `# ${title} - 小说设定文件\n\n`;
    content += `生成时间：${new Date().toLocaleString()}\n\n`;
    content += `---\n\n`;

    if (settings.storyOutline) {
      content += `## 📖 故事大纲\n\n${settings.storyOutline}\n\n`;
    }

    if (settings.plotStructure) {
      content += `## 🎯 情节结构\n\n${settings.plotStructure}\n\n`;
    }

    if (settings.characters) {
      content += `## 👥 人物设定\n\n${settings.characters}\n\n`;
    }

    content += `## 📊 篇幅规划\n\n`;
    content += `- 目标字数：${settings.targetWordCount}字\n`;
    content += `- 章节数量：${settings.chapterCount}章\n`;
    content += `- 每章字数：${Math.round(settings.targetWordCount / settings.chapterCount)}字\n\n`;

    // 增加详细的章节规划信息
    if (settings.chapters && settings.chapters.length > 0) {
      content += `## 📚 详细章节规划\n\n`;
      content += `以下是全书${settings.chapters.length}个章节的详细规划，每章包含标题、细纲、预计字数等信息。\n\n`;
      
      // 按模块分组显示章节
      const moduleGroups: { [key: number]: any[] } = {};
      settings.chapters.forEach((chapter: any) => {
        const moduleNum = chapter.moduleNumber || 1;
        if (!moduleGroups[moduleNum]) {
          moduleGroups[moduleNum] = [];
        }
        moduleGroups[moduleNum].push(chapter);
      });

      // 输出每个模块的章节
      Object.keys(moduleGroups).sort((a, b) => parseInt(a) - parseInt(b)).forEach(moduleNum => {
        content += `### 模块${moduleNum}\n\n`;
        moduleGroups[parseInt(moduleNum)].forEach((chapter: any) => {
          content += `#### 第${chapter.chapterNumber}章：${chapter.title}\n\n`;
          content += `**所属模块**：模块${chapter.moduleNumber || 1}\n\n`;
          content += `**章节细纲**：\n${chapter.outline}\n\n`;
          content += `**预计字数**：${chapter.estimatedWords || 1050}字\n\n`;
          content += `---\n\n`;
        });
      });
    }

    if (settings.chapterOutline) {
      content += `## 📚 原始章节细纲\n\n${settings.chapterOutline}\n\n`;
    }

    content += `---\n\n`;
    content += `*此文件由AI创作助手自动生成，包含小说的核心设定信息和详细章节规划。在创作各章节时请严格遵循本设定的要求。*\n`;

    return content;
  }

  /**
   * 生成并保存设置文件
   */
  static async generateAndSaveSettingFile(title: string, settings: any): Promise<string> {
    try {
      const content = this.generateSettingContent(title, settings);
      const filename = `${title}_novel_setting.md`;
      
      // 创建下载链接
      const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      return filename;
    } catch (error) {
      console.error('保存设置文件失败:', error);
      throw new Error('保存设置文件失败');
    }
  }

  /**
   * 从文件内容解析设置
   */
  static parseSettingFile(content: string): any {
    const settings: any = {
      storyOutline: '',
      plotStructure: '',
      characters: '',
      targetWordCount: 50000,
      chapterCount: 20,
      chapterOutline: ''
    };

    const lines = content.split('\n');
    let currentSection = '';
    let sectionContent = '';

    lines.forEach(line => {
      if (line.startsWith('## ')) {
        // 保存上一个section
        if (currentSection && sectionContent.trim()) {
          switch(currentSection) {
            case '📖 故事大纲':
            case '故事大纲':
              settings.storyOutline = sectionContent.trim();
              break;
            case '🎯 情节结构':
            case '情节结构':
              settings.plotStructure = sectionContent.trim();
              break;
            case '👥 人物设定':
            case '人物设定':
              settings.characters = sectionContent.trim();
              break;
            case '📚 章节细纲':
            case '章节细纲':
              settings.chapterOutline = sectionContent.trim();
              break;
          }
        }
        
        currentSection = line.replace('## ', '').replace(/[📖🎯👥📚]/g, '').trim();
        sectionContent = '';
      } else if (line.trim() && !line.startsWith('---') && !line.startsWith('# ') && !line.startsWith('*')) {
        sectionContent += line + '\n';
      }
    });

    // 处理最后一个section
    if (currentSection && sectionContent.trim()) {
      switch(currentSection) {
        case '故事大纲':
          settings.storyOutline = sectionContent.trim();
          break;
        case '情节结构':
          settings.plotStructure = sectionContent.trim();
          break;
        case '人物设定':
          settings.characters = sectionContent.trim();
          break;
        case '章节细纲':
          settings.chapterOutline = sectionContent.trim();
          break;
      }
    }

    // 提取数字信息
    const wordCountMatch = content.match(/目标字数[：:]\s*(\d+)/);
    if (wordCountMatch) {
      settings.targetWordCount = parseInt(wordCountMatch[1]);
    }

    const chapterCountMatch = content.match(/章节数量[：:]\s*(\d+)/);
    if (chapterCountMatch) {
      settings.chapterCount = parseInt(chapterCountMatch[1]);
    }

    return settings;
  }

  /**
   * 生成章节上下文信息（优化版）
   */
  static generateChapterContext(
    novel: Novel,
    currentChapter: number,
    previousChapters: any[],
    settings: any,
    chapterTitle?: string,
    chapterOutline?: string
  ): string {
    let context = `# 《${novel.title}》第${currentChapter}章创作指南\n\n`;
    
    // 第一步：novel_setting.md的核心设定
    context += `## 📋 核心设定（必须严格遵守）\n\n`;
    
    if (settings.storyOutline) {
      context += `### 📖 故事大纲\n${settings.storyOutline}\n\n`;
    }
    
    if (settings.plotStructure) {
      context += `### 🏗️ 情节结构\n${settings.plotStructure}\n\n`;
    }
    
    if (settings.characters) {
      context += `### 👥 人物设定\n${settings.characters}\n\n`;
    }
    
    // 每10章重新强调核心设定
    if (currentChapter % 10 === 1) {
      context += `⚠️ **重要提醒**：这是第${currentChapter}章，属于新一轮章节的开始。请特别重视并严格遵守上述核心设定，确保人物性格、能力、背景等保持一致，不偏离主线。\n\n`;
    }
    
    context += `---\n\n`;
    
    // 第二步：当前章节的标题和细纲
    context += `## 📝 当前章节创作要求\n\n`;
    context += `**章节编号**：第${currentChapter}章\n\n`;
    
    if (chapterTitle) {
      context += `**章节标题**：${chapterTitle}\n\n`;
    }
    
    if (chapterOutline) {
      context += `**章节细纲**：\n${chapterOutline}\n\n`;
    } else if (settings.chapters && settings.chapters[currentChapter - 1]) {
      // 从预设章节数据中获取细纲
      const plannedChapter = settings.chapters[currentChapter - 1];
      context += `**章节标题**：${plannedChapter.title}\n\n`;
      context += `**章节细纲**：\n${plannedChapter.outline}\n\n`;
      context += `**预计字数**：${plannedChapter.estimatedWords || 1050}字\n\n`;
      if (plannedChapter.moduleNumber) {
        context += `**所属模块**：模块${plannedChapter.moduleNumber}\n\n`;
      }
    }
    
    context += `---\n\n`;
    
    // 第三步：最近一章的内容（保持上下文连贯性）
    if (previousChapters.length > 0) {
      const lastChapter = previousChapters[previousChapters.length - 1];
      context += `## 📖 上一章内容回顾（用于衔接）\n\n`;
      context += `**第${lastChapter.chapterNumber}章 ${lastChapter.title}**\n\n`;
      
      // 截取上一章的完整内容，但限制长度避免token过多
      const lastContent = lastChapter.content.length > 2000 
        ? lastChapter.content.substring(0, 2000) + "..." 
        : lastChapter.content;
      
      context += `${lastContent}\n\n`;
      context += `*（以上是第${lastChapter.chapterNumber}章的完整内容，请确保第${currentChapter}章与其自然衔接）*\n\n`;
      context += `---\n\n`;
    } else {
      context += `## 📖 创作说明\n\n`;
      context += `这是小说的第一章，请开篇设定好场景，引入主要人物和核心冲突，为后续情节发展做好铺垫。\n\n`;
      context += `---\n\n`;
    }
    
    // 第四步：创作要求
    const targetWords = Math.round(settings.targetWordCount / settings.chapterCount);
    context += `## ✍️ 创作要求\n\n`;
    context += `1. **字数要求**：${targetWords}字左右（可根据情节需要适当调整）\n`;
    context += `2. **内容要求**：严格按照章节细纲创作，不偏离主线\n`;
    context += `3. **人物一致性**：确保人物性格、能力、说话方式等与核心设定一致\n`;
    context += `4. **情节连贯**：与上一章自然衔接，确保情节发展合理\n`;
    context += `5. **文笔要求**：描述生动，对话自然，节奏紧凑\n`;
    
    if (currentChapter % 10 === 1) {
      context += `6. **特殊提醒**：这是新一轮章节的开始，请特别注意巩固核心设定，防止情节偏离\n`;
    }
    
    context += `\n请开始创作第${currentChapter}章的完整内容：\n\n`;
    
    return context;
  }
}