/**
 * 前言后记节点
 */

import { GraphState } from '../graph';
import { bookStore } from '../book-generator.store';
import { callLLMWithMessages } from '../../../services/llm';
import { FOREWORD_SYSTEM_PROMPT, AFTERWORD_SYSTEM_PROMPT } from '../prompts/templates';
import { PROGRESS } from '../utils';

/**
 * 前言生成节点
 */
export async function writeForewordNode(state: typeof GraphState.State): Promise<Partial<typeof GraphState.State>> {
  console.log('[LangGraph] 生成前言, bookId:', state.bookId);
  try {
    const messages = [
      { role: 'system' as const, content: FOREWORD_SYSTEM_PROMPT },
      { role: 'user' as const, content: `请为《${state.topic}》撰写前言。` },
    ];
    const foreword = await callLLMWithMessages(messages);
    await bookStore.update(state.bookId, { foreword, progress: PROGRESS.FOREWORD_DONE });
    return { progress: PROGRESS.FOREWORD_DONE };
  } catch (error) {
    console.error('[LangGraph] 前言生成失败:', error);
    await bookStore.update(state.bookId, { errorMsg: `前言生成失败: ${error instanceof Error ? error.message : '未知'}` } as any);
    return { progress: PROGRESS.FOREWORD_DONE, error: '前言生成失败' };
  }
}

/**
 * 后记生成节点
 */
export async function writeAfterwordNode(state: typeof GraphState.State): Promise<Partial<typeof GraphState.State>> {
  console.log('[LangGraph] 生成后记, bookId:', state.bookId);
  try {
    const messages = [
      { role: 'system' as const, content: AFTERWORD_SYSTEM_PROMPT },
      { role: 'user' as const, content: `请为《${state.topic}》撰写后记。` },
    ];
    const afterword = await callLLMWithMessages(messages);
    await bookStore.update(state.bookId, { afterword });
    return { finished: true, progress: PROGRESS.AFTERWORD_DONE };
  } catch (error) {
    console.error('[LangGraph] 后记生成失败:', error);
    await bookStore.update(state.bookId, { errorMsg: `后记生成失败: ${error instanceof Error ? error.message : '未知'}` } as any);
    return { finished: true, progress: PROGRESS.AFTERWORD_DONE, error: '后记生成失败' };
  }
}
