Spaces:
Running

File size: 10,129 Bytes
20ee727
 
90be4ab
 
20ee727
 
 
 
 
 
 
3b558aa
20ee727
 
 
90be4ab
20ee727
90be4ab
 
1c2c4a2
20ee727
 
 
 
90be4ab
 
20ee727
90be4ab
 
20ee727
 
 
 
 
 
 
 
90be4ab
d04de93
 
20ee727
 
d04de93
20ee727
 
d04de93
 
 
 
 
 
 
20ee727
d04de93
20ee727
 
 
d04de93
20ee727
 
 
90be4ab
20ee727
90be4ab
 
20ee727
895402e
20ee727
 
 
 
 
 
90be4ab
20ee727
 
5f721d1
90be4ab
20ee727
90be4ab
20ee727
 
 
90be4ab
20ee727
 
 
 
 
 
90be4ab
20ee727
 
 
90be4ab
 
 
20ee727
90be4ab
 
 
 
20ee727
 
 
90be4ab
 
20ee727
 
 
 
 
90be4ab
20ee727
 
 
 
 
 
90be4ab
 
20ee727
 
 
90be4ab
20ee727
 
 
90be4ab
 
bbc6d21
 
20ee727
 
90be4ab
20ee727
bbc6d21
 
 
 
 
 
 
 
 
 
 
 
20ee727
bbc6d21
90be4ab
 
 
20ee727
 
 
90be4ab
bbc6d21
 
20ee727
90be4ab
20ee727
 
 
 
90be4ab
20ee727
 
 
 
bbc6d21
 
20ee727
90be4ab
bbc6d21
 
 
 
20ee727
 
90be4ab
 
 
 
 
bbc6d21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90be4ab
 
 
 
 
 
bbc6d21
 
 
90be4ab
 
 
 
 
20ee727
90be4ab
 
20ee727
90be4ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20ee727
90be4ab
20ee727
 
90be4ab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""
Meta Official Webhook Handler (WhatsApp & Instagram).

Uses unified MessageProcessor for message handling.
Handles verification (GET) and event notifications (POST).
"""

from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from uuid import UUID
import logging
from typing import Optional

from app.core.database import get_async_session, async_session_maker
from app.models.tenant import Tenant
from app.services.message_processor import IncomingMessage, get_message_processor
from app.services.meta_whatsapp import get_whatsapp_cloud_service
from app.services.llm_client import get_llm_client
from app.core.config import settings
from app.core.limiter import limiter

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/webhook/meta", tags=["Meta Webhooks"])


# =========================================================================
# VERIFICATION (GET)
# =========================================================================

@router.get("/{tenant_id}")
async def verify_webhook(
    tenant_id: UUID,
    mode: str = Query(alias="hub.mode"),
    token: str = Query(alias="hub.verify_token"),
    challenge: str = Query(alias="hub.challenge"),
    session: AsyncSession = Depends(get_async_session)
):
    """Handle Meta Webhook Verification Challenge."""
    logger.info(f"πŸ”” Webhook verification attempt: tenant={tenant_id}, mode={mode}, token={token[:10]}...")
    
    tenant = await session.get(Tenant, tenant_id)
    if not tenant:
        logger.error(f"❌ Tenant {tenant_id} not found")
        raise HTTPException(status_code=404, detail="Tenant not found")
    
    # Get verify token from config or use default
    wa_verify = None
    if tenant.meta_wa_config:
        wa_verify = tenant.meta_wa_config.get("verify_token")
    
    # Fallback to default token for initial setup
    default_token = "microfunnel_webhook_2024"
    
    if mode == "subscribe" and (token == wa_verify or token == default_token):
        logger.info(f"βœ… Webhook Verified for Tenant {tenant_id}")
        return int(challenge)
    
    logger.error(f"❌ Verification failed: expected={wa_verify or default_token}, got={token}")
    raise HTTPException(status_code=403, detail="Verification failed")


# =========================================================================
# EVENT NOTIFICATION (POST)
# =========================================================================

@router.post("/{tenant_id}")
@limiter.limit("5/minute")
async def handle_meta_webhook(
    tenant_id: UUID,
    request: Request,
    background_tasks: BackgroundTasks,
    session: AsyncSession = Depends(get_async_session)
):
    """Handle incoming events from Meta (WhatsApp & Instagram)."""
    try:
        data = await request.json()
        logger.info(f"πŸ“© Meta Webhook for Tenant {tenant_id}: {list(data.keys())}")
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")
    
    tenant = await session.get(Tenant, tenant_id)
    if not tenant:
        return {"status": "ignored", "reason": "tenant_not_found"}
    
    # Process in background
    background_tasks.add_task(
        process_meta_event,
        tenant_id=tenant.id,
        payload=data
    )
    
    return {"status": "ok"}


# =========================================================================
# EVENT PROCESSING
# =========================================================================

async def process_meta_event(tenant_id: UUID, payload: dict):
    """Parse and route Meta event by platform."""
    object_type = payload.get("object")
    
    if object_type == "whatsapp_business":
        await process_whatsapp_event(tenant_id, payload)
    elif object_type == "instagram":
        # TODO: Implement Instagram
        logger.info("Instagram event received (not implemented)")
    else:
        logger.warning(f"Unknown Meta object type: {object_type}")


async def process_whatsapp_event(tenant_id: UUID, payload: dict):
    """Process WhatsApp Business API event."""
    try:
        entry = payload.get("entry", [])[0]
        changes = entry.get("changes", [])[0]
        value = changes.get("value", {})
        
        if "messages" not in value:
            return  # Status update or other event
        
        message = value["messages"][0]
        contact = value.get("contacts", [])[0] if "contacts" in value else {}
        
        sender_id = message.get("from")
        sender_name = contact.get("profile", {}).get("name", f"User {sender_id}")
        
        msg_type = message.get("type")
        text = ""
        is_voice = False
        media_id = None
        media_mime = None
        
        if msg_type == "text":
            text = message["text"]["body"]
        elif msg_type == "audio":
            media_id = message["audio"]["id"]
            media_mime = message["audio"].get("mime_type")
            is_voice = True # Will transcribe
            text = "[Voice Message]" 
        elif msg_type == "image":
            media_id = message["image"]["id"]
            media_mime = message["image"].get("mime_type")
            text = message["image"].get("caption", "[Image]")
        elif msg_type == "document":
            media_id = message["document"]["id"]
            media_mime = message["document"].get("mime_type")
            text = message["document"].get("caption", "[Document]")
        else:
            text = f"[{msg_type} not supported]"
        
        # Use unified processor
        await process_whatsapp_message(
            tenant_id=tenant_id,
            sender_id=sender_id,
            sender_name=sender_name,
            text=text,
            is_voice=is_voice,
            media_id=media_id
        )
        
    except (IndexError, KeyError) as e:
        logger.error(f"Error parsing WhatsApp payload: {e}")


async def process_whatsapp_message(
    tenant_id: UUID,
    sender_id: str,
    sender_name: str,
    text: str,
    is_voice: bool = False,
    media_id: Optional[str] = None
):
    """Process WhatsApp message using unified MessageProcessor."""
    from app.core.supabase import supabase_client
    import time
    import re

    async with async_session_maker() as session:
        try:
            tenant = await session.get(Tenant, tenant_id)
            if not tenant:
                logger.error(f"Tenant {tenant_id} not found")
                return
            
            # Message Processing Vars
            media_url = None
            media_type = None

            # Handle Media Download
            if media_id:
                try:
                    wa_service = get_whatsapp_cloud_service()
                    content, mime = await wa_service.download_media(tenant, media_id)
                    
                    if is_voice:
                        try:
                            # Transcribe Voice
                            llm = get_llm_client()
                            transcript = await llm.transcribe_audio(content, mime_type=mime)
                            text = f"[Voice] {transcript}"
                        except Exception as e:
                            logger.error(f"Transcription failed: {e}")
                            text += " (Failed to transcribe)"

                    # Upload to Supabase
                    if supabase_client:
                        bucket = "chat-attachments"
                        ts = int(time.time())
                        # safe name? We don't have filename from WA easily, use generic
                        ext = mime.split('/')[-1]
                        filename = f"wa_{media_id}.{ext}"
                        path = f"{tenant.id}/incoming/{ts}_{filename}"
                        
                        supabase_client.storage.from_(bucket).upload(
                            path=path, file=content, file_options={"content-type": mime}
                        )
                        media_url = supabase_client.storage.from_(bucket).get_public_url(path)
                        media_type = mime
                        logger.info(f"πŸ“Ž WhatsApp Media uploaded: {media_url}")

                except Exception as e:
                    logger.error(f"WhatsApp Media processing failed: {e}")

            # Build incoming message
            incoming = IncomingMessage(
                channel="whatsapp",
                sender_id=sender_id,
                sender_name=sender_name,
                text=text,
                is_voice=is_voice,
                media_url=media_url,
                media_type=media_type
            )
            
            # Process with unified MessageProcessor
            processor = get_message_processor()
            result = await processor.process(session, tenant, incoming)
            
            # Send response via WhatsApp Cloud API
            wa_service = get_whatsapp_cloud_service()
            
            if result["is_voice_reply"] and settings.OPENAI_API_KEY:
                # Send voice reply
                try:
                    llm = get_llm_client()
                    audio_bytes = await llm.generate_speech(result["response_text"])
                    media_id = await wa_service.upload_media(tenant, audio_bytes)
                    await wa_service.send_audio_message(tenant, sender_id, media_id)
                    logger.info(f"πŸ—£οΈ Voice reply sent to {sender_id}")
                except Exception as e:
                    logger.error(f"Voice send failed, falling back to text: {e}")
                    await wa_service.send_text_message(tenant, sender_id, result["response_text"])
            else:
                # Send text reply
                await wa_service.send_text_message(
                    tenant=tenant,
                    to_phone=sender_id,
                    text=result["response_text"]
                )
            
            logger.info(f"βœ… WhatsApp reply sent to {sender_id}")
            
        except Exception as e:
            logger.error(f"Error processing WhatsApp message: {e}", exc_info=True)