#!/usr/bin/env python3
"""
Test different header parameter formats to find the correct structure.
"""
import os
import httpx
import json
from dotenv import load_dotenv

load_dotenv()

ACCESS_TOKEN = os.getenv("WHATSAPP_ACCESS_TOKEN")
PHONE_NUMBER_ID = os.getenv("WHATSAPP_PHONE_NUMBER_ID")
API_VERSION = "v20.0"
PHONE = "+972504370045"

test_cases = [
    {
        "name": "Variant 1: Header param as object, Body with 6 params",
        "components": [
            {
                "type": "header",
                "parameters": [
                    {"type": "text", "text": "דביר"}
                ]
            },
            {
                "type": "body",
                "parameters": [
                    {"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"}
                ]
            }
        ]
    },
    {
        "name": "Variant 2: Header with text string directly, Body with 6 params",
        "components": [
            {
                "type": "header",
                "parameters": ["דביר"]
            },
            {
                "type": "body",
                "parameters": [
                    {"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"}
                ]
            }
        ]
    },
    {
        "name": "Variant 3: No header, Body with 7 params",
        "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"}
                ]
            }
        ]
    },
    {
        "name": "Variant 4: Header with 2 params, Body with 5 params",
        "components": [
            {
                "type": "header",
                "parameters": [
                    {"type": "text", "text": "דביר"},
                    {"type": "text", "text": "כללי"}
                ]
            },
            {
                "type": "body",
                "parameters": [
                    {"type": "text", "text": "שרה"},
                    {"type": "text", "text": "אולם בן-גוריון"},
                    {"type": "text", "text": "15/06"},
                    {"type": "text", "text": "18:30"},
                    {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                ]
            }
        ]
    }
]

def test_variant(variant):
    """Test a single variant"""
    print(f"\n{'='*80}")
    print(f"Testing: {variant['name']}")
    print(f"{'='*80}")
    
    payload = {
        "messaging_product": "whatsapp",
        "to": PHONE,
        "type": "template",
        "template": {
            "name": "wedding_invitation",
            "language": {"code": "he"},
            "components": variant['components']
        }
    }
    
    # Count params
    total_params = 0
    for comp in variant['components']:
        if 'parameters' in comp:
            total_params += len(comp['parameters'])
    
    print(f"Total parameters: {total_params}")
    print(f"Component structure:")
    for comp in variant['components']:
        print(f"  - {comp['type']}: {len(comp.get('parameters', []))} params")
    
    print("\nPayload:")
    print(json.dumps(payload, indent=2, ensure_ascii=False))
    
    url = f"https://graph.instagram.com/{API_VERSION}/{PHONE_NUMBER_ID}/messages"
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    
    try:
        response = httpx.post(url, json=payload, headers=headers, timeout=10)
        
        if response.status_code == 200:
            data = response.json()
            print(f"\n✅ SUCCESS!")
            print(f"Message ID: {data.get('messages', [{}])[0].get('id', 'N/A')}")
            return True
        else:
            print(f"\n❌ FAILED (HTTP {response.status_code})")
            print(f"Error: {response.text}")
            return False
    except Exception as e:
        print(f"\n❌ Exception: {str(e)}")
        return False

if __name__ == "__main__":
    print("Testing WhatsApp Template Header Variants")
    print("="*80)
    
    results = []
    for variant in test_cases:
        success = test_variant(variant)
        results.append((variant['name'], success))
    
    print(f"\n\n{'='*80}")
    print("SUMMARY")
    print(f"{'='*80}")
    for name, success in results:
        status = "✅ SUCCESS" if success else "❌ FAILED"
        print(f"{status}: {name}")
