#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Direct API test for WhatsApp sending
Tests the actual payload being sent to Meta API
"""
import sys
import os
from dotenv import load_dotenv

# Set encoding for Windows
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# Load .env FIRST before any imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
load_dotenv()

import asyncio
from whatsapp import WhatsAppService, WhatsAppError

async def test_whatsapp_send():
    """Test WhatsApp send with real payload"""
    
    print("=" * 80)
    print("WhatsApp Direct API Test")
    print("=" * 80)
    
    # Initialize service
    try:
        service = WhatsAppService()
        print("[OK] WhatsApp Service initialized")
    except WhatsAppError as e:
        print(f"[ERROR] Failed to initialize: {e}")
        print("\n[WARNING] Make sure your .env file has:")
        print("  WHATSAPP_ACCESS_TOKEN=your_token")
        print("  WHATSAPP_PHONE_NUMBER_ID=your_id")
        return
    
    # Test data
    phone = "0504370045"  # Israeli format - should be converted to +972504370045
    guest_name = "דביר"
    groom_name = "דביר"
    bride_name = "שרה"
    venue = "אולם בן-גוריון"
    event_date = "15/06"
    event_time = "18:30"
    guest_link = "https://invy.dvirlabs.com/guest?event=ee648859"
    
    print(f"\nTest Parameters:")
    print(f"  Phone: {phone}")
    print(f"  Guest: {guest_name}")
    print(f"  Groom: {groom_name}")
    print(f"  Bride: {bride_name}")
    print(f"  Venue: {venue}")
    print(f"  Date: {event_date}")
    print(f"  Time: {event_time}")
    print(f"  Link: {guest_link}")
    
    try:
        print("\n" + "=" * 80)
        print("Sending WhatsApp message...")
        print("=" * 80)
        
        result = await service.send_wedding_invitation(
            to_phone=phone,
            guest_name=guest_name,
            partner1_name=groom_name,
            partner2_name=bride_name,
            venue=venue,
            event_date=event_date,
            event_time=event_time,
            guest_link=guest_link,
            template_name="wedding_invitation",
            language_code="he"
        )
        
        print("\n[SUCCESS]!")
        print(f"Message ID: {result.get('message_id')}")
        print(f"Status: {result.get('status')}")
        print(f"To: {result.get('to')}")
        print(f"Type: {result.get('type')}")
        
    except WhatsAppError as e:
        print(f"\n[ERROR] WhatsApp Error: {e}")
        print("\nDebugging steps:")
        print("1. Check .env file has correct tokens")
        print("2. Verify phone number format (should convert to E.164)")
        print("3. Check Meta dashboard for API limits")
        print("4. Ensure template 'wedding_invitation' is APPROVED in Meta")
        
    except Exception as e:
        print(f"\n[ERROR] Unexpected error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(test_whatsapp_send())
