#!/usr/bin/env python3
"""
Debug MailChimp content structure
"""

import os
import requests
from dotenv import load_dotenv
import json

load_dotenv()

def debug_campaign_content():
    """Debug MailChimp campaign content structure"""
    
    api_key = os.getenv('MAILCHIMP_API_KEY')
    server = os.getenv('MAILCHIMP_SERVER_PREFIX', 'us10')
    
    if not api_key:
        print("❌ No MailChimp API key found in .env")
        return
    
    base_url = f"https://{server}.api.mailchimp.com/3.0"
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
    
    # Get campaigns
    params = {
        'count': 5,
        'status': 'sent',
        'folder_id': '6a0d1e2621',  # Bi-Weekly Newsletter folder
        'sort_field': 'send_time',
        'sort_dir': 'DESC'
    }
    
    response = requests.get(f"{base_url}/campaigns", headers=headers, params=params)
    if response.status_code != 200:
        print(f"Failed to fetch campaigns: {response.status_code}")
        return
    
    campaigns = response.json().get('campaigns', [])
    
    for i, campaign in enumerate(campaigns):
        campaign_id = campaign['id']
        subject = campaign.get('settings', {}).get('subject_line', 'N/A')
        
        print(f"\n{'='*80}")
        print(f"CAMPAIGN {i+1}: {subject}")
        print(f"ID: {campaign_id}")
        print(f"{'='*80}")
        
        # Get content
        content_response = requests.get(f"{base_url}/campaigns/{campaign_id}/content", headers=headers)
        
        if content_response.status_code == 200:
            content_data = content_response.json()
            
            plain_text = content_data.get('plain_text', '')
            html = content_data.get('html', '')
            
            print(f"PLAIN_TEXT LENGTH: {len(plain_text)}")
            print(f"HTML LENGTH: {len(html)}")
            
            if plain_text:
                print(f"\nPLAIN_TEXT (first 500 chars):")
                print("-" * 40)
                print(plain_text[:500])
                print("-" * 40)
            else:
                print("\nNO PLAIN_TEXT CONTENT")
                
            if html:
                print(f"\nHTML (first 500 chars):")
                print("-" * 40)
                print(html[:500])
                print("-" * 40)
            else:
                print("\nNO HTML CONTENT")
        else:
            print(f"Failed to fetch content: {content_response.status_code}")

if __name__ == "__main__":
    debug_campaign_content()