import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';

export interface AiChatRequest {
  userId: string;
  message: string;
  context?: Record<string, any>;
  sessionId?: string;
}

export interface AiChatResponse {
  reply: string;
  sessionId: string;
  suggestions?: string[];
}

export interface AiCreditScoreRequest {
  userId: string;
  redemptionRate: number;
  breakageRate: number;
  tenureDays: number;
  satisfactionScore: number;
}

export interface AiCreditScoreResponse {
  score: number;
  level: 'A' | 'B' | 'C' | 'D' | 'F';
  factors: Record<string, number>;
}

export interface AiPricingRequest {
  couponId: string;
  faceValue: number;
  daysToExpiry: number;
  redemptionRate: number;
  liquidityPremium: number;
}

export interface AiPricingResponse {
  suggestedPrice: number;
  confidence: number;
  factors: Record<string, number>;
}

/**
 * AI Client Service - calls external AI agent cluster API.
 * The AI service is deployed separately for better scalability and management.
 * Falls back to simple responses if AI service is unavailable.
 */
@Injectable()
export class AiClientService {
  private readonly logger = new Logger('AiClient');
  private readonly baseUrl: string;
  private readonly apiKey: string;
  private readonly timeout: number;

  constructor() {
    this.baseUrl = process.env.AI_SERVICE_URL || 'http://localhost:3006';
    this.apiKey = process.env.AI_SERVICE_API_KEY || '';
    this.timeout = parseInt(process.env.AI_SERVICE_TIMEOUT || '30000', 10);
  }

  private async request<T>(path: string, body: any): Promise<T> {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);

    try {
      const response = await fetch(`${this.baseUrl}${path}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),
        },
        body: JSON.stringify(body),
        signal: controller.signal,
      });

      if (!response.ok) {
        throw new HttpException(
          `AI service error: ${response.status} ${response.statusText}`,
          HttpStatus.BAD_GATEWAY,
        );
      }

      return (await response.json()) as T;
    } catch (error) {
      if (error.name === 'AbortError') {
        throw new HttpException(
          'AI service timeout',
          HttpStatus.GATEWAY_TIMEOUT,
        );
      }
      if (error instanceof HttpException) throw error;
      this.logger.error(`AI service request failed: ${error.message}`);
      throw new HttpException(
        'AI service unavailable',
        HttpStatus.SERVICE_UNAVAILABLE,
      );
    } finally {
      clearTimeout(timeoutId);
    }
  }

  async chat(req: AiChatRequest): Promise<AiChatResponse> {
    return this.request<AiChatResponse>('/api/v1/chat', req);
  }

  async getCreditScore(
    req: AiCreditScoreRequest,
  ): Promise<AiCreditScoreResponse> {
    return this.request<AiCreditScoreResponse>('/api/v1/credit/score', req);
  }

  async getSuggestedPricing(
    req: AiPricingRequest,
  ): Promise<AiPricingResponse> {
    return this.request<AiPricingResponse>('/api/v1/pricing/suggest', req);
  }

  /**
   * Health check for the external AI service.
   */
  async healthCheck(): Promise<boolean> {
    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 5000);
      const response = await fetch(`${this.baseUrl}/health`, {
        signal: controller.signal,
      });
      clearTimeout(timeoutId);
      return response.ok;
    } catch {
      return false;
    }
  }
}
