from fastapi import APIRouter, HTTPException
import requests
from typing import List

router = APIRouter()

# Your Mailchimp API Key and list ID
API_KEY = 'YOUR_MAILCHIMP_API_KEY'
LIST_ID = 'YOUR_LIST_ID'
BASE_URL = f"https://<dc>.api.mailchimp.com/3.0"  # Replace <dc> with the datacenter specific to your Mailchimp account (e.g., us19, us20)

HEADERS = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
}


@router.post("/send_email/")
def send_email(recipients: List[str], content: str, logo_url: str):
    # 1. Add members to list
    for email in recipients:
        data = {
            "email_address": email,
            "status": "subscribed"
        }
        response = requests.post(f"{BASE_URL}/lists/{LIST_ID}/members", headers=HEADERS, json=data)
        
        # Check for errors (like if a user is already subscribed)
        if response.status_code != 200:
            return {"status": "error", "message": response.json()}

    # 2. Create a campaign
    campaign_data = {
        "type": "regular",
        "recipients": {"list_id": LIST_ID},
        "settings": {
            "subject_line": "Your Subject Here",
            "from_name": "Your Name",
            "reply_to": "your_email@example.com",
            "use_conversation": False,
            "to_name": ""
        }
    }
    response = requests.post(f"{BASE_URL}/campaigns", headers=HEADERS, json=campaign_data)
    campaign_id = response.json()["id"]

    # 3. Set up the email template
    template_content = f"<html><body><img src='{logo_url}'/><p>{content}</p></body></html>"
    content_data = {
    "html": template_content
    }
    response = requests.put(f"{BASE_URL}/campaigns/{campaign_id}/content", headers=HEADERS, json=content_data)

    # 4. Send the campaign
    response = requests.post(f"{BASE_URL}/campaigns/{campaign_id}/actions/send", headers=HEADERS)
    
    if response.status_code == 204:  # No Content means the campaign was sent successfully
        return {"status": "success", "message": "Email sent successfully."}
    else:
        return {"status": "error", "message": response.json()}
