#!/usr/bin/env python3
"""Send school outreach emails via Python smtplib - bypasses IMAP folder issues."""
import smtplib
import csv
import time
import ssl
from datetime import datetime, timezone

# Load SMTP credentials from himalaya config
import tomllib

CONFIG_PATH = "/data/.config/himalaya/config.toml"
with open(CONFIG_PATH, "rb") as f:
    config = tomllib.load(f)
smtp_cfg = config["accounts"]["immersia"]["message"]["send"]["backend"]
smtp_login = smtp_cfg["login"]
smtp_password = smtp_cfg["auth"]["raw"]
smtp_host = smtp_cfg["host"]
smtp_port = smtp_cfg["port"]

SMTP_FROM = "Emily <hello@immersiaxr.com>"
SMTP_FROM_ADDR = "hello@immersiaxr.com"

# Contacts to email this session
contacts = [
    # From 2026-03-18 scrape (personalized)
    {"school": "St Mary's Kilburn Church of England Primary School", "name": "", "title": "General enquiry", "email": "admin@stmarykilburn.camden.sch.uk"},
    {"school": "Hampstead Hill School", "name": "Miss Anne Napier", "title": "Head Teacher", "email": "anne.napier@hampsteadhillschool.co.uk"},
    {"school": "Holy Family Catholic Primary School", "name": "", "title": "General enquiry", "email": "office@holyfamily.waltham.sch.uk"},
    {"school": "Queensbridge Primary School", "name": "", "title": "General enquiry", "email": "admin@queensbridge.hackney.sch.uk"},
    {"school": "Simon Marks Jewish Primary School", "name": "Ms Sue Zion", "title": "School Office/Admissions", "email": "szion@simonmarks.hackney.sch.uk"},
    {"school": "Park Walk Primary School", "name": "Mrs Kate Webster", "title": "Headteacher", "email": "info@parkwalk.rbkc.sch.uk"},
    {"school": "Oratory Roman Catholic Primary School", "name": "Mrs Caroline Browns", "title": "Administration Officer", "email": "caroline.browns@oratory.rbkc.sch.uk"},
    {"school": "Haseltine Primary School", "name": "Sara Anderman", "title": "Head of School", "email": "admin@haseltine.lewisham.sch.uk"},
    {"school": "Rathfern Primary School", "name": "Naheeda Maharasingam", "title": "Headteacher", "email": "admin@rathfern.lewisham.sch.uk"},
    {"school": "St John's Upper Holloway CofE Primary School", "name": "", "title": "General enquiry", "email": "admin@st-johnsholloway.islington.sch.uk"},
    {"school": "St George's CofE Primary School", "name": "Mrs Sarah Collymore", "title": "Headteacher", "email": "admin@st-georges.wandsworth.sch.uk"},
    {"school": "Brandlehow Primary School", "name": "James Lacey", "title": "Headteacher", "email": "info@brandlehow.wandsworth.sch.uk"},
    {"school": "Brandlehow Primary School", "name": "Vicky Morgan", "title": "SENCO", "email": "vicky.morgan@brandlehow.wandsworth.sch.uk"},
    {"school": "Chestnuts Primary School", "name": "Jeanne Milstein", "title": "SENCO", "email": "sen@chestnutsprimary.com"},
    {"school": "Kingsmead Primary School", "name": "Evelyn Deeney", "title": "Headteacher", "email": "admin@kingsmead.hackney.sch.uk"},
    {"school": "St Mary's Bryanston Square CofE School", "name": "Mr Lee Duffy", "title": "Executive Headteacher", "email": "office@stmbs.org.uk"},
    {"school": "St Mary's Bryanston Square CofE School", "name": "Ms Breeda Cahill", "title": "Senior Administrative Officer", "email": "bcahill@stmbs.org.uk"},
    {"school": "St Stephen's CofE Primary School", "name": "", "title": "General enquiry", "email": "admin@ststephensce.lbhf.sch.uk"},
    {"school": "Wolfson Hillel Primary School", "name": "", "title": "General enquiry", "email": "hilleloffice@whjps.jcat.co.uk"},
    {"school": "St Margaret's Church of England Primary School", "name": "Anna Sullivan", "title": "Headteacher", "email": "info@stmargaretce.greenwich.sch.uk"},
    {"school": "St Margaret's Church of England Primary School", "name": "Samantha Joyce", "title": "School Business Manager", "email": "sao@stmargaretce.greenwich.sch.uk"},
    {"school": "Oasis Academy Johanna", "name": "Paul Cornall", "title": "Principal", "email": "info@oasissouthbankprimary.org"},
    {"school": "Christ Church CofE Primary School", "name": "Miss Jayne Mitchell", "title": "Executive Headteacher", "email": "admin@christchurchschool.cc"},
    # From 2026-03-19 scrape
    {"school": "Grazebrook Primary School", "name": "Nina Correa", "title": "Extended Schools Leader", "email": "ncorrea@newwavefederation.co.uk"},
    {"school": "Southwark Park Primary School", "name": "", "title": "General Contact", "email": "office@southwarkpark.southwark.sch.uk"},
    {"school": "Ysgol Gymraeg Llundain", "name": "Miss Emilia Davies", "title": "Athrawes Arweiniol (Leading Teacher)", "email": "info@ysgolgymraegllundain.co.uk"},
    {"school": "Garfield Primary School", "name": "", "title": "General Contact (pays for trips)", "email": "thandi@zambezidigital.co.uk"},
    {"school": "Ellen Wilkinson Primary School", "name": "", "title": "General Contact", "email": "info@ellenwilkinson.newham.sch.uk"},
    # Retry: previously had "cannot send message without sender" errors
    {"school": "Our Lady of Victories Catholic Primary School", "name": "", "title": "", "email": "head@ourladyofvictories.wandsworth.sch.uk"},
    {"school": "Trinity St Mary's CofE Primary School", "name": "", "title": "", "email": "sao@tsm.wandsworth.sch.uk"},
    {"school": "St Michael's CofE Primary School", "name": "", "title": "", "email": "info@stmichaels.wandsworth.sch.uk"},
    {"school": "Hallfield Primary School", "name": "", "title": "", "email": "senco@hallfieldschool.org.uk"},
    {"school": "All Souls CofE Primary School", "name": "", "title": "", "email": "office@allsoulsprimary.co.uk"},
    {"school": "St Augustines Federated Schools: CofE Primary School", "name": "", "title": "", "email": "admin@st-augustines-primary.co.uk"},
    {"school": "St Gabriel's CofE Primary School", "name": "", "title": "", "email": "office@stgabrielsprimary.co.uk"},
    {"school": "Soho Parish CofE Primary School", "name": "", "title": "", "email": "office@sohoparish.co.uk"},
    {"school": "St Peter's Eaton Square CofE Primary School", "name": "", "title": "", "email": "admin@stpeaton.org.uk"},
    {"school": "St Vincent De Paul Catholic Primary School", "name": "", "title": "", "email": "office@svpschool.co.uk"},
    {"school": "College Green School and Services", "name": "", "title": "", "email": "admin@cgss.brent.sch.uk"},
    {"school": "Wykeham Primary School", "name": "", "title": "", "email": "admin@wykeham.brent.sch.uk"},
    {"school": "Princess Frederica CofE Primary School", "name": "", "title": "", "email": "pfadmin@lifefull.org"},
    {"school": "Highgate Primary School", "name": "", "title": "", "email": "office@highgate-pri.haringey.sch.uk"},
    {"school": "Rokesly Junior School", "name": "", "title": "", "email": "admin@rokesly-jun.haringey.sch.uk"},
    {"school": "South Harringay Junior School", "name": "", "title": "", "email": "admin@shsharingey.co.uk"},
    {"school": "Lea Valley Primary School", "name": "", "title": "", "email": "admin@leavalley.haringey.sch.uk"},
    {"school": "Crowland Primary School", "name": "", "title": "", "email": "frontdesk@crowland.haringey.sch.uk"},
    {"school": "Links Primary School", "name": "", "title": "", "email": "office@links.merton.sch.uk"},
    {"school": "Wimbledon Park Primary School", "name": "", "title": "", "email": "school@wimbledonpark.merton.sch.uk"},
    {"school": "St Matthew's CofE Primary School", "name": "", "title": "", "email": "office@st-matthews.merton.sch.uk"},
    {"school": "St John Fisher RC Primary School", "name": "", "title": "", "email": "school@st-johnfisher.merton.sch.uk"},
    {"school": "St Mary Magdalen's Catholic Primary School", "name": "", "title": "", "email": "admin@st-marymagdalens.richmond.sch.uk"},
    {"school": "Whitehall Primary School", "name": "", "title": "", "email": "office@whitehall.waltham.sch.uk"},
    {"school": "South Grove Primary School", "name": "", "title": "", "email": "school@southgrove.waltham.sch.uk"},
    {"school": "Chingford CofE Primary School", "name": "", "title": "", "email": "school@ccofe.waltham.sch.uk"},
    {"school": "Stroud Green Primary School", "name": "", "title": "", "email": "office@stroudgreenprimary.com"},
    {"school": "Sacred Heart Catholic Primary School, Battersea", "name": "", "title": "", "email": "admin@sacredheart-battersea.wandsworth.sch.uk"},
    {"school": "Harry Gosling Primary School", "name": "", "title": "", "email": "admin@harrygosling.towerhamlets.sch.uk"},
    {"school": "Alexander McLeod Primary School", "name": "", "title": "", "email": "info@alex.greenwich.sch.uk"},
    {"school": "Muswell Hill Primary School", "name": "", "title": "", "email": "office@muswell-hill.haringey.sch.uk"},
]

print(f"Total contacts queued: {len(contacts)}")

TRACKING_CSV = "/data/.openclaw/workspace/Immersia XR/email_tracking.csv"
now = datetime.now(timezone.utc)

TITLES_TO_STRIP = {"Miss", "Ms", "Mrs", "Mr", "Dr", "Prof", "Sir", "Lady"}

def extract_first_name(name_str):
    if not name_str:
        return None
    parts = name_str.strip().split()
    if not parts:
        return None
    filtered = [p.rstrip('.') for p in parts if p.rstrip('.') not in TITLES_TO_STRIP]
    if filtered:
        return filtered[0]
    return parts[0]

def build_email_body(contact):
    first_name = extract_first_name(contact["name"])
    salutation = f"Hi {first_name}," if first_name else "Hi there,"
    body = f"""{salutation}

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
"""
    return body

def send_via_smtp(to_email, subject, body):
    """Send email directly via SMTP."""
    from email.message import EmailMessage
    msg = EmailMessage()
    msg["From"] = SMTP_FROM
    msg["To"] = to_email
    msg["Subject"] = subject
    msg.set_content(body)
    
    try:
        context = ssl.create_default_context()
        with smtplib.SMTP(smtp_host, smtp_port) as server:
            server.starttls(context=context)
            server.login(smtp_login, smtp_password)
            server.send_message(msg)
        return True, ""
    except Exception as e:
        return False, str(e)[:200]

def append_tracking(school, email, status, notes=""):
    with open(TRACKING_CSV, "a", newline="", encoding="utf-8") as f:
        writer = csv.writer(f, quoting=csv.QUOTE_ALL)
        writer.writerow([
            school, email,
            now.strftime("%Y-%m-%d"), now.strftime("%H:%M:%S"),
            status, "", "", "", "", "", notes
        ])

# Load already-sent emails from tracking (only SENT status)
existing = set()
try:
    with open(TRACKING_CSV, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            if row.get("Status", "").strip().upper() == "SENT":
                e = row.get("Email", "").strip().lower()
                if e:
                    existing.add(e)
except FileNotFoundError:
    pass

sent = 0
errors = 0
skipped = 0

for contact in contacts:
    email_raw = contact["email"].strip()
    email_lower = email_raw.lower()
    
    if not email_raw:
        print(f"SKIP (no email): {contact['school']}")
        skipped += 1
        continue
    
    if email_lower in existing:
        print(f"SKIP (already SENT): {contact['school']} <{email_raw}>")
        skipped += 1
        continue
    
    first_name = extract_first_name(contact["name"])
    subject = "What does a school trip inside a story feel like?"
    body = build_email_body(contact)
    
    title_note = contact["title"] if contact["title"] else "General enquiry"
    name_note = f" ({contact['name']})" if contact["name"] else ""
    note = f"Targeted - {title_note}{name_note}"
    
    print(f"[{sent+errors+1}] Sending: {contact['school']} <{email_raw}> (first name: {first_name})")
    success, err = send_via_smtp(email_raw, subject, body)
    
    if success:
        append_tracking(contact["school"], email_raw, "SENT", note)
        existing.add(email_lower)
        sent += 1
        print(f"  ✓ Sent")
    else:
        append_tracking(contact["school"], email_raw, "ERROR", err)
        errors += 1
        print(f"  ✗ Error: {err}")
    
    time.sleep(2)  # rate limiting

print(f"\n=== SESSION SUMMARY ===")
print(f"Emails sent:    {sent}")
print(f"Errors:         {errors}")
print(f"Skipped:        {skipped}")
print(f"Total queued:  {len(contacts)}")
