#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test plain text message (non-template) to verify API works
"""
import sys
import os
from dotenv import load_dotenv

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
load_dotenv()

import httpx

async def test_text_message():
    """Test sending a plain text message"""
    
    access_token = os.getenv("WHATSAPP_ACCESS_TOKEN")
    phone_id = os.getenv("WHATSAPP_PHONE_NUMBER_ID")
    
    if not access_token or not phone_id:
        print("[ERROR] Missing credentials")
        return
    
    print("Testing plain TEXT message (no template)...")
    print("=" * 80)
    
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }
    
    url = f"https://graph.facebook.com/v20.0/{phone_id}/messages"
    
    # Plain text message payload
    payload = {
        "messaging_product": "whatsapp",
        "to": "+972504370045",
        "type": "text",
        "text": {
            "body": "זה הוד דיעת! אם אתה רואה את זה, ה-API עובד!"
        }
    }
    
    print(f"\nSending text message to +972504370045...")
    print(f"Message: 'זה הודעת דיעת! אם אתה רואה את זה, ה-API עובד!'")
    
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(url, json=payload, headers=headers, timeout=10)
        
        if response.status_code in (200, 201):
            print(f"\n[SUCCESS] Text message sent!")
            data = response.json()
            msg_id = data.get('messages', [{}])[0].get('id')
            print(f"Message ID: {msg_id}")
            print("\nIf you received the message on WhatsApp, your API is working!")
            print("The template issue is separate.")
        else:
            error = response.json().get('error', {})
            print(f"\n[FAILED] {response.status_code}: {error.get('message', error)}")
    
    except Exception as e:
        print(f"\n[ERROR] {e}")

import asyncio
asyncio.run(test_text_message())
