/**
 * Voice Agent Type Definitions
 *
 * TypeScript types for ElevenLabs voice agent integration
 */

export type GCCCurrency = 'QAR' | 'SAR' | 'AED' | 'KWD' | 'BHD' | 'OMR';

export interface PromptSections {
  identity?: string;
  style?: string;
  responseGuidelines?: string;
  taskFlow?: string;
  guardrails?: string;
}

export interface CharacterNormalization {
  dateFormat?: 'arabic' | 'western' | 'auto';
  currencyFormat?: GCCCurrency | 'auto';
  phoneFormat?: 'international' | 'local';
  numberFormat?: 'arabic_eastern' | 'arabic_western' | 'auto';
}

export interface ConversationSettings {
  turnTimeout?: number;              // 1-30s
  silenceEndCallTimeout?: number;    // 5-120s
  interruptionSensitivity?: number;  // 0-1
  turnEagerness?: number;            // 0-1
  backgroundDenoising?: boolean;
  backchanneling?: boolean;
  maxDurationSeconds?: number;       // 60-3600
}

export interface VoiceSettings {
  voiceId?: string;
  speed?: number;          // 0.7-1.2
  stability?: number;      // 0-1
  similarityBoost?: number; // 0-1
  style?: number;          // 0-1 (expressiveness)
}

export interface VoiceAgentConfig {
  agentName?: string;
  language: 'ar' | 'en' | 'both';
  voiceTone: 'professional' | 'friendly' | 'custom';
  greetingMessage?: {
    ar?: string;
    en?: string;
  };
  businessHours?: {
    timezone: string;
    schedule: Array<{
      day: string;
      open: string;
      close: string;
      isOpen: boolean;
    }>;
  };
  useKnowledgeBase: boolean;
  escalationKeywords?: string[];
  customPrompt?: string;
  customVariables?: Array<{ key: string; value: string }>;
  enabledTools?: {
    checkAvailability: boolean;
    createBooking: boolean;
    cancelBooking: boolean;
    rescheduleBooking: boolean;
  };
  phoneConfig?: {
    connectionType: 'twilio_native' | 'custom_sip' | 'none';
    phoneNumber?: string;
    sipUri?: string;
  };
  promptSections?: PromptSections;
  characterNormalization?: CharacterNormalization;
  conversationSettings?: ConversationSettings;
  voiceSettings?: VoiceSettings;
}

export interface ElevenLabsAgent {
  agent_id: string;
  name: string;
  conversation_config: {
    agent: {
      prompt: {
        prompt: string;
        llm: string;
        temperature: number;
        max_tokens: number;
        tool_ids?: string[];
      };
      first_message: string;
      language: string;
    };
  };
  platform_settings?: {
    widget?: {
      avatar_url?: string;
      color?: string;
    };
  };
}

export interface CreateAgentRequest {
  name: string;
  conversation_config: {
    agent: {
      prompt: {
        prompt: string;
        llm?: string;
        temperature?: number;
        max_tokens?: number;
        tool_ids?: string[];
        knowledge_base?: Array<{
          type: 'text';
          id: string;
          name: string;
          usage_mode?: 'auto' | 'manual';
        }>;
        rag?: {
          enabled: boolean;
          embedding_model?: string;
        };
        timezone?: string;
        ignore_default_personality?: boolean;
      };
      first_message: string;
      language?: string;
      dynamic_variables?: {
        dynamic_variable_placeholders: Record<string, { value: string }>;
      };
    };
    tts?: {
      voice_id?: string;
      model_id?: string;
      stability?: number;
      similarity_boost?: number;
      speed?: number;
      style?: number;
    };
    asr?: {
      quality?: 'high' | 'low';
      keywords?: string[];
      noise_reduction?: boolean;
    };
    turn?: {
      turn_timeout?: number;
      silence_end_call_timeout?: number;
      mode?: {
        interruption_sensitivity?: number;
        turn_eagerness?: number;
        backchanneling?: boolean;
      };
    };
    conversation?: {
      max_duration_seconds?: number;
    };
  };
  use_tool_ids?: boolean;
}

export interface UpdateAgentRequest {
  name?: string;
  conversation_config?: {
    agent?: {
      prompt?: {
        prompt?: string;
        llm?: string;
        temperature?: number;
        max_tokens?: number;
        tool_ids?: string[];
        knowledge_base?: Array<{
          type: 'text';
          id: string;
          name: string;
          usage_mode?: 'auto' | 'manual';
        }>;
        rag?: {
          enabled: boolean;
          embedding_model?: string;
        };
        timezone?: string;
        ignore_default_personality?: boolean;
      };
      first_message?: string;
      language?: string;
      dynamic_variables?: {
        dynamic_variable_placeholders: Record<string, { value: string }>;
      };
    };
    tts?: {
      voice_id?: string;
      model_id?: string;
      stability?: number;
      similarity_boost?: number;
      speed?: number;
      style?: number;
    };
    asr?: {
      quality?: 'high' | 'low';
      keywords?: string[];
      noise_reduction?: boolean;
    };
    turn?: {
      turn_timeout?: number;
      silence_end_call_timeout?: number;
      mode?: {
        interruption_sensitivity?: number;
        turn_eagerness?: number;
        backchanneling?: boolean;
      };
    };
    conversation?: {
      max_duration_seconds?: number;
    };
  };
  use_tool_ids?: boolean;
}

export interface CallEvent {
  call_id: string;
  agent_id: string;
  status: 'started' | 'ended' | 'failed';
  start_time?: string;
  end_time?: string;
  duration_seconds?: number;
  transcript?: Array<{
    speaker: 'agent' | 'user';
    text: string;
    timestamp: string;
  }>;
  user_phone?: string;
  metadata?: Record<string, unknown>;
}

export interface VoiceAgentStatus {
  agent_id: string;
  is_active: boolean;
  last_call?: string;
  total_calls: number;
  avg_duration_seconds?: number;
}

export interface ConversationLog {
  id: string;
  userId: string;
  callId: string;
  agentId: string;
  startTime: Date;
  endTime?: Date;
  durationSeconds?: number;
  transcript?: Array<{ speaker: 'agent' | 'user'; text: string; timestamp: string }>;
  status: 'started' | 'ended' | 'failed';
  metadata?: Record<string, unknown>;
}

// Extended ElevenLabs Agent with phone and tools support
export interface ElevenLabsAgentExtended extends ElevenLabsAgent {
  platform_settings?: {
    widget?: {
      avatar_url?: string;
      color?: string;
    };
    phone?: {
      provider?: string;
      phone_number?: string;
      twilio?: {
        account_sid: string;
        auth_token: string;
        phone_number: string;
      };
    };
    overrides?: {
      conversation?: {
        sip_trunk_uri?: string;
      };
    };
  };
  tools?: ElevenLabsServerTool[];
}

export interface ElevenLabsServerTool {
  type: 'webhook';
  name: string;
  description: string;
  webhook: {
    url: string;
    method: 'POST';
    headers?: Record<string, string>;
  };
  parameters: {
    type: 'object';
    properties: Record<string, {
      type: string;
      description: string;
      enum?: string[];
    }>;
    required?: string[];
  };
}

export interface ServerToolCallbackPayload {
  agent_id: string;
  call_id: string;
  tool_name: string;
  parameters: Record<string, unknown>;
}
