/**
 * Assessment Expert 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,
  AssessmentExpertInput,
} from '../types/agent.types';
import { KnowledgeClientService } from '../../knowledge/knowledge-client.service';
import { buildAssessmentExpertPrompt } from '../prompts/assessment-expert-prompt';

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

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

  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 executeAssessment(input: AssessmentExpertInput): Promise<string> {
    const userMessage = this.buildUserMessage(input);
    const { result } = await this.execute(userMessage);
    return result;
  }

  private buildUserMessage(input: AssessmentExpertInput): string {
    const infoStr = Object.entries(input.userInfo)
      .map(([k, v]) => `  - ${k}: ${v}`)
      .join('\n');

    let message = `请对以下用户进行全面的移民资格评估：\n\n用户信息：\n${infoStr}`;

    if (input.targetCategories?.length) {
      message += `\n\n重点评估类别：${input.targetCategories.join(', ')}`;
    } else {
      message += '\n\n请评估所有6个移民类别（QMAS, GEP, IANG, TTPS, CIES, TECHTAS）的适合程度。';
    }

    if (input.conversationContext) {
      message += `\n\n对话背景：${input.conversationContext}`;
    }

    message += '\n\n请以 JSON 格式输出评估报告，包含每个类别的评分、推荐理由和注意事项。';

    return message;
  }
}
