#!/usr/bin/env python3
"""
Proof of concept for MailChimp API integration
Fetches campaigns from "Bi-Weekly Newsletter" folder with metrics
"""

import os
import requests
from datetime import datetime
from dotenv import load_dotenv
import json

# Load environment variables
load_dotenv()

def test_mailchimp_api():
    """Test MailChimp API connection and fetch campaigns"""
    
    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
    
    # MailChimp API base URL
    base_url = f"https://{server}.api.mailchimp.com/3.0"
    
    # Auth header
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
    
    print("🔍 Testing MailChimp API Connection...")
    print(f"Server: {server}")
    print("-" * 60)
    
    # Step 1: Test connection with ping endpoint
    try:
        response = requests.get(f"{base_url}/ping", headers=headers)
        if response.status_code == 200:
            print("✅ API connection successful!")
        else:
            print(f"❌ API connection failed: {response.status_code}")
            print(response.text)
            return
    except Exception as e:
        print(f"❌ Connection error: {e}")
        return
    
    # Step 2: Get campaign folders to find "Bi-Weekly Newsletter"
    print("\n📁 Fetching campaign folders...")
    try:
        response = requests.get(
            f"{base_url}/campaign-folders",
            headers=headers,
            params={'count': 100}
        )
        
        if response.status_code == 200:
            folders_data = response.json()
            print(f"Found {folders_data.get('total_items', 0)} folders")
            
            # Find the Bi-Weekly Newsletter folder
            target_folder_id = None
            for folder in folders_data.get('folders', []):
                print(f"  - {folder['name']} (ID: {folder['id']})")
                if folder['name'] == "Bi-Weekly Newsletter":
                    target_folder_id = folder['id']
                    print(f"    ✅ Found target folder!")
            
            if not target_folder_id:
                print("\n⚠️ 'Bi-Weekly Newsletter' folder not found")
                print("Fetching all campaigns instead...")
        else:
            print(f"❌ Failed to fetch folders: {response.status_code}")
            target_folder_id = None
    except Exception as e:
        print(f"❌ Error fetching folders: {e}")
        target_folder_id = None
    
    # Step 3: Fetch campaigns
    print("\n📊 Fetching campaigns...")
    try:
        params = {
            'count': 10,  # Get first 10 campaigns
            'status': 'sent',  # Only sent campaigns
            'sort_field': 'send_time',
            'sort_dir': 'DESC'
        }
        
        if target_folder_id:
            params['folder_id'] = target_folder_id
        
        response = requests.get(
            f"{base_url}/campaigns",
            headers=headers,
            params=params
        )
        
        if response.status_code == 200:
            campaigns_data = response.json()
            campaigns = campaigns_data.get('campaigns', [])
            
            print(f"Found {len(campaigns)} campaigns")
            print("-" * 60)
            
            # Display campaign details
            for i, campaign in enumerate(campaigns[:5], 1):  # Show first 5
                print(f"\n📧 Campaign {i}:")
                print(f"  Subject: {campaign.get('settings', {}).get('subject_line', 'N/A')}")
                print(f"  Sent: {campaign.get('send_time', 'N/A')}")
                print(f"  Status: {campaign.get('status', 'N/A')}")
                
                # Get detailed report for this campaign
                report_response = requests.get(
                    f"{base_url}/reports/{campaign['id']}",
                    headers=headers
                )
                
                if report_response.status_code == 200:
                    report = report_response.json()
                    print(f"  📈 Metrics:")
                    print(f"    - Emails Sent: {report.get('emails_sent', 0)}")
                    print(f"    - Opens: {report.get('opens', {}).get('unique_opens', 0)} ({report.get('opens', {}).get('open_rate', 0)*100:.1f}%)")
                    print(f"    - Clicks: {report.get('clicks', {}).get('unique_clicks', 0)} ({report.get('clicks', {}).get('click_rate', 0)*100:.1f}%)")
                    print(f"    - Unsubscribes: {report.get('unsubscribed', 0)}")
                
                # Get campaign content (first 200 chars)
                content_response = requests.get(
                    f"{base_url}/campaigns/{campaign['id']}/content",
                    headers=headers
                )
                
                if content_response.status_code == 200:
                    content = content_response.json()
                    plain_text = content.get('plain_text', '')
                    if plain_text:
                        preview = plain_text[:200].replace('\n', ' ')
                        print(f"  📝 Content Preview: {preview}...")
                
        else:
            print(f"❌ Failed to fetch campaigns: {response.status_code}")
            print(response.text)
            
    except Exception as e:
        print(f"❌ Error fetching campaigns: {e}")
    
    print("\n" + "=" * 60)
    print("MailChimp API test complete!")

if __name__ == "__main__":
    test_mailchimp_api()