/**
 * ElevenLabs Workflow Service
 *
 * Creates and manages template-based workflows for voice agents.
 * Uses pre-built templates rather than a full graph editor.
 */

import { logger } from '@/lib/logger';
import { WORKFLOW_TEMPLATES, WorkflowTemplate } from '@/lib/config/voice-agent-workflow-templates';

export class ElevenLabsWorkflowService {
  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;
  }

  /**
   * Get available workflow templates
   */
  getTemplates(): WorkflowTemplate[] {
    return WORKFLOW_TEMPLATES;
  }

  /**
   * Get a specific template by ID
   */
  getTemplate(templateId: string): WorkflowTemplate | undefined {
    return WORKFLOW_TEMPLATES.find(t => t.id === templateId);
  }

  /**
   * Build a prompt from a workflow template with customizations
   */
  buildWorkflowPrompt(
    templateId: string,
    customization: Record<string, string>
  ): string {
    const template = this.getTemplate(templateId);
    if (!template) throw new Error(`Template not found: ${templateId}`);

    // Build a structured prompt from the workflow nodes
    const steps = template.nodes
      .filter(n => n.type === 'prompt' || n.type === 'tool_call')
      .map((n, i) => {
        const label = n.label.en;
        if (n.type === 'tool_call') {
          return `${i + 1}. [ACTION] ${label}: Use the ${n.toolName} tool.`;
        }
        return `${i + 1}. ${label}: ${n.prompt || ''}`;
      });

    // Inject customization values
    let prompt = `Follow this conversation flow:\n\n${steps.join('\n')}`;

    for (const [key, value] of Object.entries(customization)) {
      prompt += `\n\n${key}: ${value}`;
    }

    return prompt;
  }

  /**
   * Apply a workflow template to an agent by updating its prompt
   */
  async applyToAgent(
    agentId: string,
    templateId: string,
    customization: Record<string, string>
  ): Promise<{ success: boolean; error?: string }> {
    try {
      const workflowPrompt = this.buildWorkflowPrompt(templateId, customization);

      logger.info('Applying workflow template to agent', { agentId, templateId });

      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: {
                prompt: workflowPrompt,
              },
            },
          },
        }),
      });

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

      logger.info('Workflow template applied', { agentId, templateId });
      return { success: true };
    } catch (error) {
      logger.error('Error applying workflow template', error);
      return { success: false, error: 'Failed to apply workflow template' };
    }
  }
}

export const elevenLabsWorkflowService = new ElevenLabsWorkflowService();
