/**
 * Agents Module
 * 多 Agent 系统 NestJS 模块
 *
 * 注册所有 Agent 服务：
 * - CoordinatorAgentService（主协调器，替代 ClaudeAgentServiceV2）
 * - 6 个专家 Agent
 * - ContextInjectorService（动态上下文注入）
 */

import { Module, Global } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import Anthropic from '@anthropic-ai/sdk';
import { ConfigService } from '@nestjs/config';

// Coordinator
import { CoordinatorAgentService } from './coordinator/coordinator-agent.service';
import { ContextInjectorService } from './coordinator/context-injector.service';
import { InputGateService } from './coordinator/input-gate.service';

// Specialists
import { PolicyExpertService } from './specialists/policy-expert.service';
import { AssessmentExpertService } from './specialists/assessment-expert.service';
import { StrategistService } from './specialists/strategist.service';
import { ObjectionHandlerService } from './specialists/objection-handler.service';
import { CaseAnalystService } from './specialists/case-analyst.service';
import { MemoryManagerService } from './specialists/memory-manager.service';

// External dependencies
import { KnowledgeModule } from '../knowledge/knowledge.module';
import { TokenUsageService } from '../claude/token-usage.service';
import { ImmigrationToolsService } from '../claude/tools/immigration-tools.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TokenUsageORM } from '../database/postgres/entities/token-usage.orm';

// MCP Integration
import { McpModule } from './mcp/mcp.module';

// Payment Integration
import { PaymentModule } from '../payment/payment.module';

// Evaluation Gate
import { EvaluationGateService } from './coordinator/evaluation-gate.service';
import { EvaluationRuleORM } from '../database/postgres/entities/evaluation-rule.orm';
import { EvaluationRulePostgresRepository } from '../database/postgres/repositories/evaluation-rule.repository';
import { EVALUATION_RULE_REPOSITORY } from '../../domain/repositories/evaluation-rule.repository.interface';

/**
 * Anthropic Client Provider
 * 共享的 Anthropic SDK 实例，所有 Agent 共用
 */
const AnthropicClientProvider = {
  provide: Anthropic,
  useFactory: (configService: ConfigService) => {
    const baseUrl = configService.get<string>('ANTHROPIC_BASE_URL');
    const isProxyUrl =
      baseUrl &&
      (baseUrl.includes('67.223.119.33') || baseUrl.match(/^\d+\.\d+\.\d+\.\d+/));

    if (isProxyUrl) {
      console.log(`[AgentsModule] Using Anthropic proxy: ${baseUrl}`);
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
    }

    return new Anthropic({
      apiKey: configService.get<string>('ANTHROPIC_API_KEY'),
      baseURL: baseUrl || undefined,
    });
  },
  inject: [ConfigService],
};

@Global()
@Module({
  imports: [
    ConfigModule,
    KnowledgeModule,
    TypeOrmModule.forFeature([TokenUsageORM, EvaluationRuleORM]),
    McpModule,
    PaymentModule,
  ],
  providers: [
    // Shared Anthropic client
    AnthropicClientProvider,

    // Token tracking
    TokenUsageService,

    // Legacy tool implementations (production-tested, reused by Coordinator)
    ImmigrationToolsService,

    // Context injection
    ContextInjectorService,

    // Specialist agents
    PolicyExpertService,
    AssessmentExpertService,
    StrategistService,
    ObjectionHandlerService,
    CaseAnalystService,
    MemoryManagerService,

    // Input gate
    InputGateService,

    // Evaluation gate
    {
      provide: EVALUATION_RULE_REPOSITORY,
      useClass: EvaluationRulePostgresRepository,
    },
    EvaluationGateService,

    // Main coordinator
    CoordinatorAgentService,
  ],
  exports: [
    CoordinatorAgentService,
    EvaluationGateService,
    EVALUATION_RULE_REPOSITORY,
    // Export specialists for potential direct use
    PolicyExpertService,
    AssessmentExpertService,
    StrategistService,
    ObjectionHandlerService,
    CaseAnalystService,
    MemoryManagerService,
  ],
})
export class AgentsModule {}
