#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test different component combinations
"""
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_combinations():
    """Test different component combinations"""
    
    access_token = os.getenv("WHATSAPP_ACCESS_TOKEN")
    phone_id = os.getenv("WHATSAPP_PHONE_NUMBER_ID")
    
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }
    
    url = f"https://graph.facebook.com/v20.0/{phone_id}/messages"
    
    tests = [
        ("Header only (1 param)", {
            "messaging_product": "whatsapp",
            "to": "+972504370045",
            "type": "template",
            "template": {
                "name": "wedding_invitation",
                "language": {"code": "he"},
                "components": [{
                    "type": "header",
                    "parameters": [{"type": "text", "text": "דביר"}]
                }]
            }
        }),
        ("Header (1) + Body (6)", {
            "messaging_product": "whatsapp",
            "to": "+972504370045",
            "type": "template",
            "template": {
                "name": "wedding_invitation",
                "language": {"code": "he"},
                "components": [
                    {"type": "header", "parameters": [{"type": "text", "text": "דביר"}]},
                    {"type": "body", "parameters": [
                        {"type": "text", "text": "p1"},
                        {"type": "text", "text": "p2"},
                        {"type": "text", "text": "p3"},
                        {"type": "text", "text": "p4"},
                        {"type": "text", "text": "p5"},
                        {"type": "text", "text": "p6"}
                    ]}
                ]
            }
        }),
        ("Body only (1)", {
            "messaging_product": "whatsapp",
            "to": "+972504370045",
            "type": "template",
            "template": {
                "name": "wedding_invitation",
                "language": {"code": "he"},
                "components": [{
                    "type": "body",
                    "parameters": [{"type": "text", "text": "דביר"}]
                }]
            }
        }),
    ]
    
    print("Testing component combinations...")
    print("=" * 80 + "\n")
    
    for desc, payload in tests:
        print(f"[Test] {desc}")
        
        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()
                msg_id = data.get('messages', [{}])[0].get('id')
                print(f"  Message ID: {msg_id}")
                return True
            else:
                error = response.json().get('error', {})
                msg = error.get('message', error)
                print(f"  [FAILED] {msg}")
        
        except Exception as e:
            print(f"  [ERROR] {e}")
        
        print()
    
    return False

import asyncio
result = asyncio.run(test_combinations())
if not result:
    print("\n" + "=" * 80)
    print("IMPORTANT: None of the standard structures worked!")
    print("\nPlease verify in Meta Business Manager:")
    print("1. Go to Message Templates")
    print("2. Check template name (must be exactly: 'wedding_invitation')")
    print("3. Check it's APPROVED status")
    print("4. Check how many {{}} variables are shown in the template body")
    print("5. Verify the template language is 'Hebrew' (he)")
    print("\nThe template might need to be recreated.")
    print("=" * 80)
