#!/usr/bin/env python3
"""Test 2 header params + 5 body params structure."""
import sys
import asyncio
from dotenv import load_dotenv

sys.path.insert(0, '.')
load_dotenv()

import os
import httpx
import json

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

test_cases = [
    {
        "name": "Header 2 params (firstname lastname) + Body 5 params",
        "components": [
            {
                "type": "header",
                "parameters": [
                    {"type": "text", "text": "Dvir"},
                    {"type": "text", "text": "Horev"}
                ]
            },
            {
                "type": "body",
                "parameters": [
                    {"type": "text", "text": "החתן"},
                    {"type": "text", "text": "הכלה"},
                    {"type": "text", "text": "הרמוניה בגן"},
                    {"type": "text", "text": "15/06"},
                    {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                ]
            }
        ]
    },
    {
        "name": "Header 2 params + Body 5 params (with time)",
        "components": [
            {
                "type": "header",
                "parameters": [
                    {"type": "text", "text": "Dvir"},
                    {"type": "text", "text": "Horev"}
                ]
            },
            {
                "type": "body",
                "parameters": [
                    {"type": "text", "text": "החתן"},
                    {"type": "text", "text": "הכלה"},
                    {"type": "text", "text": "הרמוניה בגן"},
                    {"type": "text", "text": "15/06 18:30"},
                    {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                ]
            }
        ]
    },
    {
        "name": "Header 1 param + Body 5 params + Footer 1",
        "components": [
            {
                "type": "header",
                "parameters": [
                    {"type": "text", "text": "Dvir"}
                ]
            },
            {
                "type": "body",
                "parameters": [
                    {"type": "text", "text": "החתן"},
                    {"type": "text", "text": "הכלה"},
                    {"type": "text", "text": "הרמוניה בגן"},
                    {"type": "text", "text": "15/06"},
                    {"type": "text", "text": "18:30"}
                ]
            },
            {
                "type": "footer",
                "parameters": [
                    {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                ]
            }
        ]
    },
]

def test_variant(variant):
    """Test a single variant"""
    print(f"\nTesting: {variant['name']}")
    print(f"{'='*60}")
    
    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}")
    for comp in variant['components']:
        param_count = len(comp.get('parameters', []))
        print(f"  - {comp['type']}: {param_count} params")
    
    url = f"https://graph.instagram.com/v20.0/{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()
            msg_id = data.get('messages', [{}])[0].get('id', 'N/A')
            print(f"✅ SUCCESS! Message ID: {msg_id}")
            return True, msg_id, payload
        else:
            error_data = response.json()
            error_msg = error_data.get('error', {}).get('message', 'Unknown')
            print(f"❌ FAILED - {error_msg}")
            return False, None, None
    except Exception as e:
        print(f"❌ Exception: {str(e)}")
        return False, None, None

if __name__ == "__main__":
    print("Testing Header + Body Parameter Combinations")
    print("="*60)
    
    for variant in test_cases:
        success, msg_id, payload = test_variant(variant)
        if success:
            print(f"\n🎉 FOUND IT! {variant['name']}")
            print(f"\nWinning payload structure:")
            print(json.dumps(payload, indent=2, ensure_ascii=False))
            break
