/**
 * 聊天界面组件
 * 使用 readline question() 实现多行输入
 */

const readline = require('readline');
const { CLEAR_LINE, CYAN, DIM, GREEN, RED, YELLOW, colored } = require('../utils/ansi');
const { renderLine } = require('../utils/markdown');

class ChatUI {
  constructor(agent, options = {}) {
    this.agent = agent;
    this.rl = null;
    this.lines = []; // 多行输入的累积

    // 流式模式（默认开启）
    this.stream = options.stream !== false;

    // 会话管理
    this.sessionId = options.sessionId || 'cli_default';
    this.sessionPlugin = null;

    // 如果 agent 有 framework，获取 SessionPlugin
    if (agent.framework) {
      this.sessionPlugin = agent.framework.pluginManager.get('session');
      // 确保会话存在
      if (this.sessionPlugin) {
        this.sessionPlugin.getOrCreateSession(this.sessionId, {
          metadata: { platform: 'cli' },
        });
      }
    }
  }

  /**
   * 启动聊天界面
   */
  start() {
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
      crlfDelay: Infinity,
    });

    this.printWelcome();
    this.promptUser();
  }

  /**
   * 打印欢迎信息
   */
  printWelcome() {
    console.log(`${colored('Foliko', CYAN)} - 持续对话聊天`);
    console.log(
      `${colored('Ctrl+C', DIM)} 退出 | ${colored('连续两次回车', DIM)} 发送多行 | ${colored('!!', DIM)} 立即发送\n`
    );
  }

  /**
   * 获取多行输入
   */
  getMultilineInput() {
    return new Promise((resolve) => {
      const lines = [];

      const question = (isFirst) => {
        const prompt = isFirst ? colored('> ', GREEN) : colored('- ', DIM);
        this.rl.question(prompt, (input) => {
          // 输入 !! 立即结束
          if (input.trim() === '!!') {
            const result = lines.join('\n').trim();
            resolve(result);
            return;
          }

          // 空行：结束输入并发送（第一次空行就发送）
          if (input.trim() === '') {
            const result = lines.join('\n').trim();
            resolve(result);
            return;
          }

          // 非空行：添加到 lines，继续输入
          lines.push(input);
          question(false);
        });
      };

      question(true);
    });
  }

  /**
   * 提示用户输入
   */
  async promptUser() {
    try {
      const input = await this.getMultilineInput();

      if (!input) {
        await this.promptUser();
        return;
      }

      // 退出命令
      if (input.toLowerCase() === 'exit' || input.toLowerCase() === 'quit') {
        console.log('再见！');
        this.rl.close();
        return;
      }

      // 发送消息
      await this.sendMessage(input);

      // 继续等待下一条消息
      await this.promptUser();
    } catch (err) {
      console.error(`\n${colored('[错误]', RED)} ${err.message}`);
      await this.promptUser();
    }
  }

  /**
   * 发送消息并显示响应
   */
  async sendMessage(message) {
    // 用于打断的标志
    let interrupted = false;

    // 设置打断处理
    const interruptHandler = () => {
      if (!interrupted) {
        interrupted = true;
        console.log(`\n${colored('[中断]', RED)} 输出已中断`);
      }
    };

    // 监听 Ctrl+C
    process.on('SIGINT', interruptHandler);

    let fullResponse = '';

    try {
      const renderState = { inThink: false, inCodeBlock: false };
      const runWithContext = this.agent.framework?.runWithContext.bind(this.agent.framework);
      const { sessionId } = this;

      if (this.stream) {
        // 流式模式
        console.log(colored('● ', GREEN));

        let lineBuffer = '';
        await runWithContext({ sessionId }, async () => {
          for await (const chunk of this.agent.chatStream(message, { sessionId })) {
            if (interrupted) break;

            if (chunk.type === 'text') {
              fullResponse += chunk.text;
              lineBuffer += chunk.text;

              while (lineBuffer.includes('\n')) {
                if (interrupted) break;

                const nlIndex = lineBuffer.indexOf('\n');
                const line = lineBuffer.substring(0, nlIndex);
                lineBuffer = lineBuffer.substring(nlIndex + 1);
                if (line.trim()) {
                  console.log(renderLine(line, renderState));
                }
              }
            } else if (chunk.type === 'tool-call') {
              console.log(`\n${colored('[工具调用]', YELLOW)} ${chunk.toolName}`);
            } else if (chunk.type === 'error') {
              console.error(`\n${colored('[错误]', RED)} ${chunk.error}`);
            }
          }
        });

        if (lineBuffer.trim() && !interrupted) {
          console.log(renderLine(lineBuffer, renderState));
        }
      } else {
        // 非流式模式
        console.log(colored('○ ', CYAN) + '处理中...\n');

        const result = await runWithContext({ sessionId }, async () => {
          return await this.agent.chat(message, { sessionId });
        });

        if (interrupted) return;

        fullResponse = result.message;

        // 一次性渲染完整响应
        const lines = fullResponse.split('\n');
        for (const line of lines) {
          if (line.trim()) {
            console.log(renderLine(line, renderState));
          } else {
            console.log();
          }
        }
      }
    } catch (err) {
      if (!interrupted) {
        console.error(`\n${colored('[错误]', RED)} ${err.message}\n`);
      }
    } finally {
      process.removeListener('SIGINT', interruptHandler);
    }
  }
}

module.exports = { ChatUI };
