import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
}

interface VAPIMessage {
  role: string
  message?: string
  content?: string
  time: number
  endTime?: number
  secondsFromStart: number
  duration?: number
  source?: string
  metadata?: any
  toolCalls?: any[]
  tool_calls?: any[]
  toolCallId?: string
  tool_call_id?: string
  name?: string
  result?: string
}

interface VAPIAnalysis {
  summary?: string
  successEvaluation?: string
}

interface VAPIArtifact {
  messages: VAPIMessage[]
  messagesOpenAIFormatted?: VAPIMessage[]
  transcript?: string
  recordingUrl?: string
  stereoRecordingUrl?: string
  pcapUrl?: string
  logUrl?: string
}

interface VAPIWebhookPayload {
  message: {
    timestamp: number
    type: string
    analysis?: VAPIAnalysis
    artifact?: VAPIArtifact
    call?: {
      id?: string
      phoneNumberId?: string
      customerId?: string
      assistantId?: string
      cost?: number
      costBreakdown?: {
        stt?: number
        llm?: number
        tts?: number
        twilio?: number
        total?: number
      }
    }
  }
}

serve(async (req) => {
  // Handle CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

  try {
    // Only accept POST requests
    if (req.method !== 'POST') {
      return new Response(
        JSON.stringify({ error: 'Method not allowed' }),
        { status: 405, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    // Parse the webhook payload
    const payload: VAPIWebhookPayload = await req.json()
    console.log('Received VAPI webhook:', JSON.stringify(payload, null, 2))

    // Validate payload structure
    if (!payload.message || payload.message.type !== 'end-of-call-report') {
      console.log('Ignoring non-end-of-call-report webhook:', payload.message?.type)
      return new Response(
        JSON.stringify({ status: 'ignored', reason: 'Not an end-of-call-report' }),
        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    const { message } = payload
    const { timestamp, analysis, artifact, call } = message

    // Create Supabase client with service role key (bypasses RLS for webhook)
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!
    const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
    const supabase = createClient(supabaseUrl, supabaseKey)

    // Extract transcript from messages
    let transcript = artifact?.transcript || ''
    if (!transcript && artifact?.messages) {
      // Build transcript from messages
      const transcriptParts = artifact.messages
        .filter(msg => msg.role === 'user' || msg.role === 'bot' || msg.role === 'assistant')
        .map(msg => {
          const speaker = msg.role === 'user' ? 'Customer' : 'Assistant'
          const text = msg.message || msg.content || ''
          return `[${speaker}]: ${text}`
        })
      transcript = transcriptParts.join('\n\n')
    }

    // Calculate call duration from messages
    let durationSeconds = 0
    if (artifact?.messages && artifact.messages.length > 0) {
      const lastMessage = artifact.messages[artifact.messages.length - 1]
      durationSeconds = Math.round(lastMessage.secondsFromStart)
    }

    // Determine call outcome based on analysis
    let callOutcome = 'pending'
    if (analysis?.successEvaluation === 'true' || analysis?.successEvaluation === true) {
      callOutcome = 'resolved'
    } else if (analysis?.successEvaluation === 'false' || analysis?.successEvaluation === false) {
      callOutcome = 'not_interested'
    }

    // Prepare call log data
    const callLogData = {
      // VAPI-specific fields
      vapi_call_id: call?.id || crypto.randomUUID(),
      vapi_timestamp: timestamp,
      messages: artifact?.messages || [],
      analysis: analysis || {},

      // Recording URLs
      recording_url: artifact?.recordingUrl,
      stereo_recording_url: artifact?.stereoRecordingUrl,
      pcap_url: artifact?.pcapUrl,
      log_url: artifact?.logUrl,

      // Call metadata
      assistant_id: call?.assistantId,
      phone_number_id: call?.phoneNumberId,
      customer_number: call?.customerId,

      // Call status and outcome
      status: 'completed',
      call_outcome: callOutcome,
      call_type: 'inbound', // VAPI calls are typically inbound

      // Transcript and summary
      transcript: transcript,
      summary: analysis?.summary || '',

      // Timing
      started_at: new Date(timestamp).toISOString(),
      ended_at: new Date(timestamp).toISOString(),
      duration_seconds: durationSeconds,

      // Costs
      cost_stt: call?.costBreakdown?.stt || 0,
      cost_llm: call?.costBreakdown?.llm || 0,
      cost_tts: call?.costBreakdown?.tts || 0,
      cost_twilio: call?.costBreakdown?.twilio || 0,
      cost_total: call?.costBreakdown?.total || call?.cost || 0,
      cost_totals: call?.costBreakdown?.total || call?.cost || 0,

      // Timestamps
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    }

    console.log('Inserting call log:', callLogData)

    // Insert call log into database
    const { data, error } = await supabase
      .from('call_logs')
      .insert([callLogData])
      .select()
      .single()

    if (error) {
      console.error('Error inserting call log:', error)
      return new Response(
        JSON.stringify({ error: 'Failed to store call log', details: error.message }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      )
    }

    console.log('Call log stored successfully:', data.id)

    // Return success response
    return new Response(
      JSON.stringify({
        status: 'success',
        call_log_id: data.id,
        message: 'Call log stored successfully'
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )

  } catch (error) {
    console.error('Error processing VAPI webhook:', error)
    return new Response(
      JSON.stringify({
        error: 'Internal server error',
        details: error instanceof Error ? error.message : 'Unknown error'
      }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )
  }
})
