/**
 * Strategist Specialist Agent
 * 策略顾问 Agent — 提供对话策略建议（仅对 Coordinator 可见，用户不可见）
 */

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

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

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

  protected getTools(): ToolDefinition[] {
    return [
      {
        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> {
    if (toolName === 'get_user_context') {
      try {
        return await this.knowledgeClient.getUserContext(
          toolInput.query as string,
        ) || '无用户历史记录。';
      } catch (error) {
        return '用户记忆检索暂时不可用。';
      }
    }
    return `Unknown tool: ${toolName}`;
  }

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

  private buildUserMessage(input: StrategistInput): string {
    const collectedInfoStr = Object.entries(input.collectedInfo)
      .map(([k, v]) => `  - ${k}: ${v}`)
      .join('\n') || '  (尚未收集任何信息)';

    return [
      '请分析当前对话状态并提供策略建议：',
      '',
      `对话摘要: ${input.conversationSummary}`,
      `当前轮次: ${input.currentTurnCount}`,
      `已收集信息:\n${collectedInfoStr}`,
      `用户情绪: ${input.userSentiment || '未知'}`,
      `已完成评估: ${input.hasAssessment ? '是' : '否'}`,
      `已转化: ${input.hasConverted ? '是' : '否'}`,
      '',
      '请返回 JSON 格式的策略建议，包含:',
      '- currentStage: 当前所处咨询阶段',
      '- recommendedNextAction: 建议的下一步行动',
      '- missingInfoPriorities: 需要优先收集的信息',
      '- conversionSignals: 检测到的转化信号',
      '- toneAdjustment: 语气调整建议',
      '- urgencyLevel: 紧急程度 (low/medium/high)',
    ].join('\n');
  }
}
