#!/usr/bin/env python3
"""Send school outreach emails via himalaya."""

import csv
import subprocess
import re
from datetime import datetime

# Configuration
CONTACTS_FILE = "/data/.openclaw/workspace/Immersia XR/scraped_contacts_results.csv"
TRACKING_FILE = "/data/.openclaw/workspace/Immersia XR/email_tracking.csv"
MAX_EMAILS = 50

# Email template
EMAIL_SUBJECT = "What does a school trip inside a story feel like?"

EMAIL_BODY = """Hi {first_name},

Are you planning any school trips to London this term?

We run Immersia XR at Waterloo — the UK's first XR walking theatre experience where students physically walk through story worlds using XR headsets, linked to the curriculum. No tech skills needed. Fully supervised. 2 minutes from Waterloo Station.

Curriculum-linked worlds:
— Alice in Wonderland (English / Creative Writing)
— Moon Landing (Science / History / STEM)
— Journey to the Centre of the Earth (Geography / Science)
— 20,000 Leagues Under the Sea (Geography / Marine Biology)
— Tales of Aladdin (World Cultures / PSHE / RE)
— Eternal Tang Dynasty (History / World Cultures)

What teachers need to know:
— £18/pupil (double world), £12/pupil (single world)
— 1 teacher free per 6 pupils
— 45-minute experience, easy in/out logistics
— Full risk assessment provided
— 4.8 stars on Google, 10,000+ visitors
— Available weekday mornings and afternoons from late April

Would any dates work for your class? Just reply and I'll hold a slot.

Emily
Schools & Education Coordinator, Immersia XR
hello@immersiaxr.com
The Sidings, Waterloo Station, London SE1 7LY

---
To unsubscribe from future emails: https://immersiaxr.com/unsubscribe"""

def is_valid_email(email):
    """Check if email is valid."""
    if not email or email.strip() == "":
        return False
    email = email.strip()
    # Invalid patterns
    invalid_patterns = [
        "N/A", "Not Found", "Not found", "n/a",
        "user@domain.com", "logo@2x.png",
        "http://", "https://"
    ]
    for pattern in invalid_patterns:
        if pattern.lower() in email.lower():
            return False
    # Must have @ and .
    if "@" not in email or "." not in email:
        return False
    return True

def get_first_name(name):
    """Extract first name from full name."""
    if not name or name.strip() == "":
        return None
    return name.strip().split()[0] if name.strip() else None

def load_sent_emails():
    """Load already sent emails from tracking file."""
    sent = set()
    try:
        with open(TRACKING_FILE, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            for row in reader:
                email = row.get('Email', '').strip().lower()
                status = row.get('Status', '').strip().upper()
                # Only count successfully sent
                if email and status == 'SENT':
                    sent.add(email)
    except FileNotFoundError:
        pass
    return sent

def load_contacts():
    """Load contacts with valid emails."""
    contacts = []
    sent_emails = load_sent_emails()
    
    with open(CONTACTS_FILE, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            school = row.get('School Name', '').strip()
            coordinator = row.get('Coordinator Name', '').strip()
            title = row.get('Trip Contact Title', '').strip()
            email = row.get('Trip Contact Email', '').strip()
            
            if is_valid_email(email) and email.lower() not in sent_emails:
                first_name = get_first_name(coordinator)
                if not first_name:
                    first_name = "there"  # Generic fallback
                contacts.append({
                    'school': school,
                    'coordinator': coordinator,
                    'title': title,
                    'email': email,
                    'first_name': first_name
                })
    
    return contacts

def send_email(to_email, subject, body):
    """Send email via himalaya."""
    # Build raw email message
    message = f"""From: Emily <hello@immersiaxr.com>
To: {to_email}
Subject: {subject}
Content-Type: text/plain; charset=utf-8

{body}"""
    
    try:
        result = subprocess.run(
            ["himalaya", "message", "send", "--quiet", message],
            capture_output=True,
            text=True,
            timeout=30
        )
        if result.returncode == 0:
            return True, "SENT"
        else:
            return False, f"ERROR: {result.stderr[:200]}"
    except Exception as e:
        return False, f"EXCEPTION: {str(e)[:100]}"

def update_tracking(school, email, status, notes=""):
    """Append to tracking file."""
    now = datetime.now()
    date_str = now.strftime("%Y-%m-%d")
    time_str = now.strftime("%H:%M:%S")
    
    with open(TRACKING_FILE, 'a', encoding='utf-8') as f:
        f.write(f'"{school}","{email}","{date_str}","{time_str}","{status}","","","","","","{notes}"\n')

def main():
    print("Loading contacts...")
    contacts = load_contacts()
    print(f"Found {len(contacts)} valid emails not yet sent")
    
    to_send = contacts[:MAX_EMAILS]
    print(f"Processing {len(to_send)} emails (max {MAX_EMAILS})")
    
    sent_count = 0
    error_count = 0
    
    for i, contact in enumerate(to_send, 1):
        print(f"[{i}/{len(to_send)}] Sending to {contact['school']} ({contact['email']})...")
        
        body = EMAIL_BODY.format(first_name=contact['first_name'])
        
        success, status = send_email(contact['email'], EMAIL_SUBJECT, body)
        
        if success:
            update_tracking(contact['school'], contact['email'], "SENT", "General outreach")
            sent_count += 1
            print(f"  ✓ Sent")
        else:
            update_tracking(contact['school'], contact['email'], status[:50], "Failed")
            error_count += 1
            print(f"  ✗ {status[:80]}")
    
    print(f"\n=== SUMMARY ===")
    print(f"Emails sent: {sent_count}")
    print(f"Errors: {error_count}")
    print(f"Remaining available: {len(contacts) - MAX_EMAILS}")

if __name__ == "__main__":
    main()