# PATCH: Fix transcription not being saved

## Problem
Recording webhook fires BEFORE communication is logged.
Transcript lookup fails because the record doesn't exist yet.

## Solution  
1. Try multiple lookup methods (call_sid, external_id)
2. If no match, save to pending_transcripts table
3. When /calls/log is called, check for pending transcript and attach it

## Changes needed:

### 1. In transcribeRecording() function (around line 570), replace the lookup:

OLD:
```javascript
// Try to find and update the communications record by CallSid
const { data: comm, error: findError } = await supabase
  .from('communications')
  .select('id, metadata')
  .eq('metadata->>call_sid', callSid)
  .single();
```

NEW:
```javascript
// Try multiple methods to find the communication record
let comm = null;

// Method 1: Try metadata.call_sid (outbound calls logged via /calls/log)
const { data: comm1 } = await supabase
  .from('communications')
  .select('id, metadata, lead_id')
  .eq('metadata->>call_sid', callSid)
  .single();

if (comm1) {
  comm = comm1;
  console.log(`[Recording] Found communication by metadata.call_sid: ${comm.id}`);
}

// Method 2: Try external_id (voicemails and inbound calls)
if (!comm) {
  const { data: comm2 } = await supabase
    .from('communications')
    .select('id, metadata, lead_id')
    .eq('external_id', callSid)
    .single();

  if (comm2) {
    comm = comm2;
    console.log(`[Recording] Found communication by external_id: ${comm.id}`);
  }
}

// Method 3: If we have leadId from cache, find recent call for that lead
if (!comm && leadId) {
  const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000).toISOString();
  const { data: comm3 } = await supabase
    .from('communications')
    .select('id, metadata, lead_id')
    .eq('lead_id', leadId)
    .in('type', ['call_outbound', 'call_inbound'])
    .gte('created_at', fiveMinutesAgo)
    .order('created_at', { ascending: false })
    .limit(1)
    .single();

  if (comm3) {
    comm = comm3;
    console.log(`[Recording] Found communication by recent call for lead: ${comm.id}`);
  }
}
```

### 2. After the "if no communication found" block, add pending transcript save:

Replace:
```javascript
} else {
  console.log('[Recording] No communication record or leadId - transcript not saved');
}
```

With:
```javascript
} else {
  // Save orphaned transcript for later attachment
  console.log(`[Recording] No match found - saving orphaned transcript for CallSid ${callSid}`);
  
  const { error: orphanError } = await supabase
    .from('copilot_sessions')
    .insert({
      lead_id: leadId || null,
      transcript: transcript,
      recording_url: recordingUrl,
      duration_seconds: duration,
      metadata: {
        orphaned: true,
        call_sid: callSid,
        awaiting_communication: true,
        transcribed_at: new Date().toISOString()
      }
    });

  if (orphanError) {
    console.error('[Recording] Failed to save orphaned transcript:', orphanError.message);
  } else {
    console.log(`[Recording] Orphaned transcript saved for CallSid ${callSid}`);
  }
}
```

### 3. In calls.js POST /log endpoint (around line 110), add orphan check:

After the communication insert, add:
```javascript
// Check for orphaned transcript from recording webhook
if (callSid) {
  const { data: orphan } = await supabase
    .from('copilot_sessions')
    .select('id, transcript, recording_url, duration_seconds')
    .eq('metadata->>call_sid', callSid)
    .eq('metadata->>orphaned', 'true')
    .single();

  if (orphan && orphan.transcript) {
    console.log(`[Calls] Found orphaned transcript for CallSid ${callSid}, attaching...`);
    
    // Update the communication we just created
    const { error: attachError } = await supabase
      .from('communications')
      .update({
        metadata: {
          ...comm.metadata,
          transcript: orphan.transcript,
          recording_url: orphan.recording_url,
          recording_duration: orphan.duration_seconds,
          auto_transcribed: true,
          attached_from_orphan: true
        }
      })
      .eq('id', comm.id);

    if (!attachError) {
      // Delete the orphan record
      await supabase.from('copilot_sessions').delete().eq('id', orphan.id);
      console.log(`[Calls] Transcript attached and orphan cleaned up`);
    }
  }
}
```
