import { Injectable, Logger } from '@nestjs/common';
import {
  AssessmentCommand,
  AssessmentCommandType,
  AssessmentCommandDto,
} from '../dto/assessment-command.dto';

@Injectable()
export class AssessmentCommandParser {
  private readonly logger = new Logger(AssessmentCommandParser.name);

  // 支持的命令前缀
  private readonly commandPrefixes = [
    '/assessment',
    '/测评',
    '/eval',
    '/测评评估',
  ];

  // 命令映射
  private readonly commandMap: Record<string, AssessmentCommandType> = {
    start: AssessmentCommandType.START,
    开始: AssessmentCommandType.START,
    answer: AssessmentCommandType.ANSWER,
    回答: AssessmentCommandType.ANSWER,
    status: AssessmentCommandType.STATUS,
    状态: AssessmentCommandType.STATUS,
    result: AssessmentCommandType.RESULT,
    结果: AssessmentCommandType.RESULT,
    help: AssessmentCommandType.HELP,
    帮助: AssessmentCommandType.HELP,
    cancel: AssessmentCommandType.CANCEL,
    取消: AssessmentCommandType.CANCEL,
  };

  /**
   * 解析消息是否为测评命令
   */
  parse(message: string): AssessmentCommand | null {
    const trimmed = message.trim();

    // 检查是否是测评命令
    const isCommand = this.commandPrefixes.some((prefix) =>
      trimmed.toLowerCase().startsWith(prefix.toLowerCase()),
    );

    if (!isCommand) {
      return null;
    }

    try {
      // 解析命令
      const parts = trimmed.split(/\s+/);
      const commandTypeStr = parts[1]?.toLowerCase();

      // 查找命令类型
      const commandType = this.commandMap[commandTypeStr];

      if (!commandType) {
        // 未知命令，返回帮助
        return {
          type: AssessmentCommandType.HELP,
          parameters: [],
          rawMessage: message,
          timestamp: new Date(),
        };
      }

      // 获取参数（跳过命令前缀和命令类型）
      const parameters = parts.slice(2);

      return {
        type: commandType,
        parameters,
        rawMessage: message,
        timestamp: new Date(),
      };
    } catch (error) {
      this.logger.error(
        `Failed to parse assessment command: ${error.message}`,
        error,
      );
      return null;
    }
  }

  /**
   * 检查消息是否为测评命令
   */
  isAssessmentCommand(message: string): boolean {
    const trimmed = message.trim().toLowerCase();
    return this.commandPrefixes.some((prefix) =>
      trimmed.startsWith(prefix.toLowerCase()),
    );
  }

  /**
   * 获取命令帮助文本
   */
  getHelpText(language: string = 'zh'): string {
    if (language === 'zh') {
      return `
**人才测评机器人帮助**

命令格式：
- \`/assessment start [templateId]\` - 开始测评
- \`/assessment answer [answer]\` - 提交答案
- \`/assessment status\` - 查看测评状态
- \`/assessment result\` - 获取测评结果
- \`/assessment help\` - 显示帮助
- \`/assessment cancel\` - 取消测评

说明：
- 如果未指定知识库/模板，将使用机器人配置的默认知识库
- 也可直接回复答案，无需命令前缀
            `.trim();
    } else {
      return `
**Assessment Bot Help**

Commands:
- \`/assessment start [templateId]\` - Start assessment
- \`/assessment answer [answer]\` - Submit answer
- \`/assessment status\` - Check assessment status
- \`/assessment result\` - Get assessment results
- \`/assessment help\` - Show help
- \`/assessment cancel\` - Cancel assessment

Note:
- If no knowledge base/template is specified, the bot's default knowledge base will be used
- You can also reply directly with your answer without command prefix
            `.trim();
    }
  }
}
