/**
 * Policy 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, PolicyExpertInput } from '../types/agent.types';
import { KnowledgeClientService } from '../../knowledge/knowledge-client.service';
import { buildPolicyExpertPrompt } from '../prompts/policy-expert-prompt';

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

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

  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'],
              description: '移民类别代码（可选，缩小搜索范围）',
            },
          },
          required: ['query'],
        },
      },
    ];
  }

  protected async executeTool(
    toolName: string,
    toolInput: Record<string, unknown>,
  ): Promise<string> {
    if (toolName === 'search_knowledge') {
      const RAG_CONFIDENCE_THRESHOLD = 0.55;
      try {
        const ragResult = await this.knowledgeClient.retrieveKnowledge({
          query: toolInput.query as string,
          category: toolInput.category as string | undefined,
        });

        if (!ragResult || !ragResult.content) {
          return '[KB_EMPTY] 知识库未找到相关内容。如需回答，必须在回复中明确标注"基于AI训练数据，可能不是最新信息"。';
        }

        const hasConfident = ragResult.sources?.some(
          (s) => s.similarity >= RAG_CONFIDENCE_THRESHOLD,
        );

        if (!hasConfident) {
          return `[KB_LOW_CONFIDENCE] 知识库找到以下内容但置信度较低，引用时请标注"仅供参考，可能不是最新信息"：\n\n${ragResult.content}`;
        }

        return ragResult.content;
      } catch (error) {
        this.logger.error(`Knowledge search failed: ${error}`);
        return '[KB_ERROR] 知识库搜索暂时不可用。如需回答，必须在回复中明确标注"基于AI训练数据，可能不是最新信息"。';
      }
    }
    return `Unknown tool: ${toolName}`;
  }

  /**
   * Typed execute method for Coordinator to call
   */
  async executeQuery(input: PolicyExpertInput): Promise<string> {
    const userMessage = this.buildUserMessage(input);
    const { result } = await this.execute(userMessage);
    return result;
  }

  private buildUserMessage(input: PolicyExpertInput): string {
    let message = input.query;
    if (input.category) {
      message = `[类别: ${input.category}] ${message}`;
    }
    if (input.includeProcessSteps) {
      message += '\n\n请包含详细的申请流程步骤。';
    }
    if (input.includeRequirements) {
      message += '\n\n请列出所有申请条件和要求。';
    }
    return message;
  }
}
