#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test with all potential components (header, body, buttons)
"""
import sys
import os
from dotenv import load_dotenv

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

import httpx
import json

async def test_payload():
    """Test different payload structures"""
    
    # Get config
    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 in .env")
        return
    
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }
    
    url = f"https://graph.facebook.com/v20.0/{phone_id}/messages"
    
    # Payload with ONLY body parameters (what we're sending now)
    payload_1 = {
        "messaging_product": "whatsapp",
        "to": "+972504370045",
        "type": "template",
        "template": {
            "name": "wedding_invitation",
            "language": {"code": "he"},
            "components": [
                {
                    "type": "body",
                    "parameters": [
                        {"type": "text", "text": "דביר"},
                        {"type": "text", "text": "דביר"},
                        {"type": "text", "text": "שרה"},
                        {"type": "text", "text": "אולם בן-גוריון"},
                        {"type": "text", "text": "15/06"},
                        {"type": "text", "text": "18:30"},
                        {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                    ]
                }
            ]
        }
    }
    
    # Payload WITH header component (if template has header)
    payload_2 = {
        "messaging_product": "whatsapp",
        "to": "+972504370045",
        "type": "template",
        "template": {
            "name": "wedding_invitation",
            "language": {"code": "he"},
            "components": [
                {
                    "type": "header",
                    "parameters": []  # Empty header
                },
                {
                    "type": "body",
                    "parameters": [
                        {"type": "text", "text": "דביר"},
                        {"type": "text", "text": "דביר"},
                        {"type": "text", "text": "שרה"},
                        {"type": "text", "text": "אולם בן-גוריון"},
                        {"type": "text", "text": "15/06"},
                        {"type": "text", "text": "18:30"},
                        {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                    ]
                }
            ]
        }
    }
    
    # Payload with header + button (if template has buttons)
    payload_3 = {
        "messaging_product": "whatsapp",
        "to": "+972504370045",
        "type": "template",
        "template": {
            "name": "wedding_invitation",
            "language": {"code": "he"},
            "components": [
                {
                    "type": "body",
                    "parameters": [
                        {"type": "text", "text": "דביר"},
                        {"type": "text", "text": "דביר"},
                        {"type": "text", "text": "שרה"},
                        {"type": "text", "text": "אולם בן-גוריון"},
                        {"type": "text", "text": "15/06"},
                        {"type": "text", "text": "18:30"},
                        {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                    ]
                },
                {
                    "type": "button",
                    "sub_type": "url",
                    "parameters": []  # Empty button parameters
                }
            ]
        }
    }
    
    print("Testing different payload structures...")
    print("=" * 80)
    
    for i, payload in enumerate([payload_1, payload_2, payload_3], 1):
        print(f"\n[Test {i}] Components: {[c['type'] for c in payload['template']['components']]}")
        
        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"  [SUCCESS] Message sent!")
                data = response.json()
                print(f"  Message ID: {data.get('messages', [{}])[0].get('id')}")
                return
            else:
                error = response.json().get('error', {}).get('message', 'Unknown error')
                print(f"  [FAILED] {response.status_code}: {error}")
        
        except Exception as e:
            print(f"  [ERROR] {e}")

import asyncio
asyncio.run(test_payload())
