/**
 * ElevenLabs Conversation Analysis Service
 *
 * Configures success evaluation criteria and data collection for voice agent calls.
 * Retrieves analysis results per conversation.
 */

import { logger } from '@/lib/logger';

export interface SuccessEvaluationCriterion {
  name: string;
  description: string;
  type: 'boolean' | 'scale';
}

export interface DataCollectionField {
  name: string;
  description: string;
  type: 'string' | 'number' | 'boolean' | 'date';
  required: boolean;
}

export interface ConversationAnalysisResult {
  conversationId: string;
  evaluationResults?: Array<{
    name: string;
    result: boolean | number;
    rationale?: string;
  }>;
  collectedData?: Record<string, unknown>;
}

export class ElevenLabsAnalysisService {
  private baseUrl = 'https://api.elevenlabs.io/v1';

  private getApiKey(): string {
    const apiKey = process.env.ELEVENLABS_API_KEY;
    if (!apiKey) throw new Error('ELEVENLABS_API_KEY environment variable is required');
    return apiKey;
  }

  /**
   * Configure success evaluation criteria on an agent
   */
  async configureSuccessEvaluation(
    agentId: string,
    criteria: SuccessEvaluationCriterion[]
  ): Promise<{ success: boolean; error?: string }> {
    try {
      logger.info('Configuring success evaluation', { agentId, criteriaCount: criteria.length });

      const response = await fetch(`${this.baseUrl}/convai/agents/${agentId}`, {
        method: 'PATCH',
        headers: {
          'xi-api-key': this.getApiKey(),
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          conversation_config: {
            agent: {
              prompt: {
                evaluation_criteria: criteria.map(c => ({
                  name: c.name,
                  description: c.description,
                  type: c.type,
                })),
              },
            },
          },
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        logger.error('Failed to configure success evaluation', new Error(response.statusText), { errorData });
        return { success: false, error: `Configuration failed: ${response.status} ${response.statusText}` };
      }

      logger.info('Success evaluation configured', { agentId });
      return { success: true };
    } catch (error) {
      logger.error('Error configuring success evaluation', error);
      return { success: false, error: 'Failed to configure success evaluation' };
    }
  }

  /**
   * Configure data collection fields on an agent
   */
  async configureDataCollection(
    agentId: string,
    fields: DataCollectionField[]
  ): Promise<{ success: boolean; error?: string }> {
    try {
      logger.info('Configuring data collection', { agentId, fieldCount: fields.length });

      const response = await fetch(`${this.baseUrl}/convai/agents/${agentId}`, {
        method: 'PATCH',
        headers: {
          'xi-api-key': this.getApiKey(),
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          conversation_config: {
            agent: {
              prompt: {
                data_collection: fields.map(f => ({
                  name: f.name,
                  description: f.description,
                  type: f.type,
                  required: f.required,
                })),
              },
            },
          },
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        logger.error('Failed to configure data collection', new Error(response.statusText), { errorData });
        return { success: false, error: `Configuration failed: ${response.status} ${response.statusText}` };
      }

      logger.info('Data collection configured', { agentId });
      return { success: true };
    } catch (error) {
      logger.error('Error configuring data collection', error);
      return { success: false, error: 'Failed to configure data collection' };
    }
  }

  /**
   * Get analysis results for a conversation
   */
  async getConversationAnalysis(
    conversationId: string
  ): Promise<ConversationAnalysisResult | { error: string }> {
    try {
      logger.info('Fetching conversation analysis', { conversationId });

      const response = await fetch(
        `${this.baseUrl}/convai/conversations/${conversationId}`,
        {
          method: 'GET',
          headers: {
            'xi-api-key': this.getApiKey(),
          },
        }
      );

      if (!response.ok) {
        return { error: `Fetch failed: ${response.status} ${response.statusText}` };
      }

      const data = await response.json();
      return {
        conversationId,
        evaluationResults: data.analysis?.evaluation_results,
        collectedData: data.analysis?.collected_data,
      };
    } catch (error) {
      logger.error('Error fetching conversation analysis', error);
      return { error: 'Failed to fetch conversation analysis' };
    }
  }
}

export const elevenLabsAnalysisService = new ElevenLabsAnalysisService();
