/**
 * Objection Handler Specialist Agent
 * 异议处理 Agent — 处理用户的疑虑、犹豫和反对意见
 */

import { Injectable } from '@nestjs/common';
import Anthropic from '@anthropic-ai/sdk';
import { BaseSpecialistService } from './base-specialist.service';
import {
  AGENT_CONFIGS,
  SpecialistAgentType,
  ToolDefinition,
  ObjectionHandlerInput,
} from '../types/agent.types';
import { KnowledgeClientService } from '../../knowledge/knowledge-client.service';
import { buildObjectionHandlerPrompt } from '../prompts/objection-handler-prompt';

@Injectable()
export class ObjectionHandlerService extends BaseSpecialistService {
  constructor(
    anthropicClient: Anthropic,
    private readonly knowledgeClient: KnowledgeClientService,
  ) {
    super(AGENT_CONFIGS[SpecialistAgentType.OBJECTION_HANDLER], anthropicClient);
  }

  protected getSystemPrompt(): string {
    return buildObjectionHandlerPrompt();
  }

  protected getTools(): ToolDefinition[] {
    return [
      {
        name: 'search_knowledge',
        description: '搜索知识库获取事实依据，用于回应用户的疑虑和反对意见',
        input_schema: {
          type: 'object',
          properties: {
            query: { type: 'string', description: '搜索查询' },
            category: {
              type: 'string',
              enum: ['QMAS', 'GEP', 'IANG', 'TTPS', 'CIES', 'TECHTAS'],
            },
          },
          required: ['query'],
        },
      },
      {
        name: 'get_user_context',
        description: '获取用户历史信息，了解之前的疑虑和沟通记录',
        input_schema: {
          type: 'object',
          properties: {
            query: { type: 'string', description: '检索查询' },
          },
          required: ['query'],
        },
      },
    ];
  }

  protected async executeTool(
    toolName: string,
    toolInput: Record<string, unknown>,
  ): Promise<string> {
    switch (toolName) {
      case 'search_knowledge': {
        try {
          return await this.knowledgeClient.search(
            toolInput.query as string,
            toolInput.category as string | undefined,
          ) || '未找到相关内容。';
        } catch (error) {
          return '知识库搜索暂时不可用。';
        }
      }
      case 'get_user_context': {
        try {
          return await this.knowledgeClient.getUserContext(
            toolInput.query as string,
          ) || '无用户历史记录。';
        } catch (error) {
          return '用户记忆检索暂时不可用。';
        }
      }
      default:
        return `Unknown tool: ${toolName}`;
    }
  }

  /**
   * Typed execute method
   */
  async handleObjection(input: ObjectionHandlerInput): Promise<string> {
    const userMessage = this.buildUserMessage(input);
    const { result } = await this.execute(userMessage);
    return result;
  }

  private buildUserMessage(input: ObjectionHandlerInput): string {
    let message = `用户提出了以下疑虑或反对意见，请帮助处理：\n\n用户疑虑：${input.objection}`;

    message += `\n\n用户背景：${input.userContext}`;

    if (input.previousObjections?.length) {
      message += `\n\n之前的疑虑：\n${input.previousObjections.map((o, i) => `  ${i + 1}. ${o}`).join('\n')}`;
    }

    message += '\n\n请以 JSON 格式返回处理建议，包含：';
    message += '\n- objectionCategory: 疑虑类型（价格、时间、风险、信任、竞品等）';
    message += '\n- empathyResponse: 共情回应';
    message += '\n- factualRebuttal: 事实依据反驳';
    message += '\n- successStoryReference: 相关成功案例（如有）';
    message += '\n- suggestedResponse: 建议回复';
    message += '\n- followUpQuestion: 跟进问题';

    return message;
  }
}
