import { Injectable, Inject, Logger } from '@nestjs/common';
import {
  AI_AGENT_CLIENT,
  IAiAgentClient,
  AgentStatsResponse,
  AgentTopQuestion,
  AgentSessionsResponse,
  AgentSatisfactionMetrics,
} from '../../domain/ports/ai-agent.client.interface';

export interface AiModuleInfo {
  id: string;
  name: string;
  description: string;
  enabled: boolean;
  accuracy: number;
  lastUpdated: string;
  config: Record<string, any>;
}

@Injectable()
export class AdminAgentService {
  private readonly logger = new Logger(AdminAgentService.name);

  // In-memory module config (in production, this would come from DB or external service)
  private moduleConfigs: Map<string, Record<string, any>> = new Map();

  constructor(
    @Inject(AI_AGENT_CLIENT) private readonly agentClient: IAiAgentClient,
  ) {}

  /**
   * Get aggregate AI agent session stats.
   * Tries external agent cluster first, falls back to mock data.
   */
  async getStats(): Promise<AgentStatsResponse> {
    try {
      return await this.agentClient.getStats();
    } catch (error) {
      this.logger.warn(`External agent stats unavailable: ${error.message}`);
    }

    // Mock stats when external agent is unavailable
    return {
      sessionsToday: 127,
      totalSessions: 14582,
      avgResponseTimeMs: 1240,
      satisfactionScore: 4.2,
      activeModules: 4,
    };
  }

  /**
   * Get most commonly asked questions.
   */
  async getTopQuestions(limit = 10): Promise<AgentTopQuestion[]> {
    try {
      return await this.agentClient.getTopQuestions(limit);
    } catch (error) {
      this.logger.warn(`External agent top-questions unavailable: ${error.message}`);
    }

    // Mock data
    return [
      { question: 'How do I redeem a coupon?', count: 342, category: 'coupon' },
      { question: 'What are the trading fees?', count: 281, category: 'trading' },
      { question: 'How to complete KYC verification?', count: 256, category: 'account' },
      { question: 'When will my settlement be processed?', count: 198, category: 'settlement' },
      { question: 'How to transfer coupons?', count: 167, category: 'coupon' },
      { question: 'What is breakage?', count: 145, category: 'finance' },
      { question: 'How to contact support?', count: 132, category: 'support' },
      { question: 'Can I cancel an order?', count: 121, category: 'order' },
      { question: 'How does AI pricing work?', count: 98, category: 'ai' },
      { question: 'What currencies are supported?', count: 87, category: 'general' },
    ].slice(0, limit);
  }

  /**
   * Get AI module status and accuracy info.
   */
  async getModules(): Promise<AiModuleInfo[]> {
    const now = new Date().toISOString();

    return [
      {
        id: 'chat',
        name: 'AI Chat Assistant',
        description: 'Conversational AI for user support and Q&A',
        enabled: true,
        accuracy: 0.89,
        lastUpdated: now,
        config: this.moduleConfigs.get('chat') || { maxTokens: 2048, temperature: 0.7 },
      },
      {
        id: 'credit',
        name: 'Credit Scoring',
        description: 'AI-powered credit risk assessment for issuers and users',
        enabled: true,
        accuracy: 0.92,
        lastUpdated: now,
        config: this.moduleConfigs.get('credit') || { modelVersion: 'v2', threshold: 0.6 },
      },
      {
        id: 'pricing',
        name: 'Pricing Engine',
        description: 'AI pricing suggestions for secondary market trading',
        enabled: true,
        accuracy: 0.85,
        lastUpdated: now,
        config: this.moduleConfigs.get('pricing') || { modelVersion: 'v1', confidenceThreshold: 0.7 },
      },
      {
        id: 'anomaly',
        name: 'Anomaly Detection',
        description: 'Real-time transaction anomaly and fraud detection',
        enabled: true,
        accuracy: 0.94,
        lastUpdated: now,
        config: this.moduleConfigs.get('anomaly') || { riskThreshold: 50, alertEnabled: true },
      },
    ];
  }

  /**
   * Update configuration for a specific AI module.
   */
  async configureModule(moduleId: string, config: Record<string, any>): Promise<AiModuleInfo> {
    // Store config locally (in production: persist to DB)
    const existing = this.moduleConfigs.get(moduleId) || {};
    const merged = { ...existing, ...config };
    this.moduleConfigs.set(moduleId, merged);

    this.logger.log(`Module ${moduleId} config updated: ${JSON.stringify(merged)}`);

    // Try to propagate to external agent
    try {
      await this.agentClient.configureModule(moduleId, merged);
    } catch {
      this.logger.warn(`Could not propagate config to external agent for module ${moduleId}`);
    }

    const modules = await this.getModules();
    const updated = modules.find((m) => m.id === moduleId);
    return (
      updated || {
        id: moduleId,
        name: moduleId,
        description: '',
        enabled: true,
        accuracy: 0,
        lastUpdated: new Date().toISOString(),
        config: merged,
      }
    );
  }

  /**
   * Get recent AI chat sessions.
   */
  async getSessions(
    page: number,
    limit: number,
  ): Promise<AgentSessionsResponse> {
    try {
      return await this.agentClient.getSessions(page, limit);
    } catch (error) {
      this.logger.warn(`External agent sessions unavailable: ${error.message}`);
    }

    // Mock session data
    const now = Date.now();
    const items = Array.from({ length: Math.min(limit, 10) }, (_, i) => ({
      sessionId: `session-${1000 - i - (page - 1) * limit}`,
      userId: `user-${Math.floor(Math.random() * 500) + 1}`,
      messageCount: Math.floor(Math.random() * 20) + 1,
      startedAt: new Date(now - (i + (page - 1) * limit) * 3600000).toISOString(),
      lastMessageAt: new Date(now - (i + (page - 1) * limit) * 3600000 + 1800000).toISOString(),
      satisfactionRating: Math.random() > 0.3 ? Math.floor(Math.random() * 2) + 4 : null,
    }));

    return { items, total: 100, page, limit };
  }

  /**
   * Get satisfaction metrics for AI chat sessions.
   */
  async getSatisfactionMetrics(): Promise<AgentSatisfactionMetrics> {
    try {
      return await this.agentClient.getSatisfactionMetrics();
    } catch (error) {
      this.logger.warn(`External agent satisfaction unavailable: ${error.message}`);
    }

    // Mock satisfaction data
    return {
      averageRating: 4.2,
      totalRatings: 8943,
      distribution: {
        '1': 234,
        '2': 412,
        '3': 1089,
        '4': 3456,
        '5': 3752,
      },
      trend: [
        { period: '2025-01', rating: 4.0 },
        { period: '2025-02', rating: 4.1 },
        { period: '2025-03', rating: 4.1 },
        { period: '2025-04', rating: 4.2 },
        { period: '2025-05', rating: 4.3 },
        { period: '2025-06', rating: 4.2 },
      ],
    };
  }
}
