#!/usr/bin/env python3
"""
Test different parameter distributions with focus on header variations.
"""
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"

print(f"Token: {ACCESS_TOKEN[:50]}...")
print(f"Phone ID: {PHONE_NUMBER_ID}")
print(f"Testing with phone: {PHONE}\n")

test_cases = [
    {
        "name": "Header 2 params + Body 5 params (7 total)",
        "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 6 params (8 total)",
        "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": "18:30"},
                    {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                ]
            }
        ]
    },
    {
        "name": "Header 1 param + Body 7 params (8 total)",
        "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": "text", "text": "—"},
                    {"type": "text", "text": "https://invy.dvirlabs.com/guest"}
                ]
            }
        ]
    },
    {
        "name": "Body only 7 params (7 total) - NO HEADER",
        "components": [
            {
                "type": "body",
                "parameters": [
                    {"type": "text", "text": "Dvir"},
                    {"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": "Body only 8 params (8 total) - NO HEADER",
        "components": [
            {
                "type": "body",
                "parameters": [
                    {"type": "text", "text": "Dvir"},
                    {"type": "text", "text": "Horev"},
                    {"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": "Header 1 (name) + Body 6 (groom, bride, venue, date, time, link) - ORIGINAL",
        "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": "—"},
                    {"type": "text", "text": "https://invy.dvirlabs.com/guest?event=ee648859-2cbf-487a-bdce-bd780d90e6e3"}
                ]
            }
        ]
    }
]

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']:
        param_count = len(comp.get('parameters', []))
        print(f"  - {comp['type']}: {param_count} params")
    
    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')}")
            print(f"\n🎉 FOUND THE CORRECT STRUCTURE!")
            print(f"\nPayload structure that worked:")
            print(json.dumps(payload, indent=2, ensure_ascii=False))
            return True
        else:
            error_data = response.json()
            error_msg = error_data.get('error', {}).get('message', 'Unknown error')
            print(f"\n❌ FAILED (HTTP {response.status_code})")
            print(f"Error: {error_msg}")
            return False
    except Exception as e:
        print(f"\n❌ Exception: {str(e)}")
        return False

if __name__ == "__main__":
    print("WhatsApp Template Parameter Distribution Test")
    print("="*80)
    
    results = []
    for variant in test_cases:
        success = test_variant(variant)
        results.append((variant['name'], success))
        if success:
            break
    
    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}")
