/**
 * Case Analyst Specialist Agent
 * 案例分析 Agent — 检索和分析成功案例
 *
 * 使用 Haiku 模型（主要是检索和格式化，不需要强推理）
 */

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

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

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

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

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

    let message = `请为以下用户检索和分析相关的成功案例：\n\n用户背景：\n${profileStr}`;
    message += `\n\n目标移民类别：${input.targetCategory}`;

    if (input.focusArea) {
      message += `\n\n重点关注：${input.focusArea}`;
    }

    message += '\n\n请以 JSON 格式返回案例分析，包含：';
    message += '\n- matchedCases: 匹配的案例列表（含 summary, similarityFactors, outcome, timeline）';
    message += '\n- keyTakeaways: 关键启示';

    return message;
  }
}
