// src/utils/aiService.ts
import 'dotenv/config';

export interface AIServiceConfig {
  endpoint: string;
  apiKey: string;
  model: string;
}

export interface AICallOptions {
  temperature?: number;
  timeout?: number;
}

export interface AIResponse {
  content: string;
  usage?: {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
}

class AIService {
  private config: AIServiceConfig;
  private defaultOptions: AICallOptions;

  constructor() {
    this.config = {
      endpoint: this.getRequiredEnv('AI_ANALYZER_ENDPOINT'),
      apiKey: this.getRequiredEnv('AI_ANALYZER_API_KEY'),
      model: this.getRequiredEnv('AI_ANALYZER_MODEL')
    };

    this.defaultOptions = {
      temperature: 0.3,
      timeout: 60000
    };

    console.log('[AI-SERVICE] Initialized with model:', this.config.model);
  }

  private getRequiredEnv(key: string): string {
    const value = process.env[key];
    if (!value) {
      throw new Error(`Missing required environment variable: ${key}`);
    }
    return value;
  }

  async callAI(prompt: string, options: AICallOptions = {}): Promise<AIResponse> {
    const mergedOptions = { ...this.defaultOptions, ...options };
    
    console.log('[AI-SERVICE] Making API call:', {
      promptLength: prompt.length,
      temperature: mergedOptions.temperature
    });

    const headers: Record<string, string> = {
      'Content-Type': 'application/json'
    };
    
    if (this.config.apiKey) {
      headers['Authorization'] = `Bearer ${this.config.apiKey}`;
    }
    
    const requestBody = {
      model: this.config.model,
      messages: [{ role: 'user', content: prompt }],
      temperature: mergedOptions.temperature
    };
    
    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), mergedOptions.timeout);

      const response = await fetch(`${this.config.endpoint}/v1/chat/completions`, {
        method: 'POST',
        headers,
        body: JSON.stringify(requestBody),
        signal: controller.signal
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        const errorText = await response.text();
        console.error('[AI-SERVICE] API Error:', response.status, errorText);
        throw new Error(`AI API error: ${response.status} - ${errorText}`);
      }

      const data = await response.json();
      const content = data.choices?.[0]?.message?.content;
      
      if (!content) {
        console.error('[AI-SERVICE] No response content from AI model');
        throw new Error('No response from AI model');
      }

      console.log('[AI-SERVICE] API call successful:', {
        responseLength: content.length,
        usage: data.usage
      });

      return {
        content: content.trim(),
        usage: data.usage
      };
      
    } catch (error) {
      if (error.name === 'AbortError') {
        console.error('[AI-SERVICE] Request timeout');
        throw new Error('AI request timeout');
      }
      
      console.error('[AI-SERVICE] API call failed:', error.message);
      throw error;
    }
  }

  async callMicroTaskAI(prompt: string): Promise<AIResponse> {
    return this.callAI(prompt, { 
      temperature: 0.3,
      timeout: 30000 
    });
  }

  estimateTokens(text: string): number {
    return Math.ceil(text.length / 4);
  }

  getConfig(): AIServiceConfig {
    return { ...this.config };
  }
}

export const aiService = new AIService();