#!/usr/bin/env python3
"""
EDEN SENDER (INTEGRATED AUTH)
1. Loads Credentials from /Eden/SECRETS/email_config.json (Same as Harvester)
2. Reads drafts from /Eden/OUTBOX
3. Asks PERMISSION (Strategy), not PASSWORD (Logistics).
"""
import smtplib
import os
import ssl
import json
import shutil
from email.message import EmailMessage

OUTBOX = "/Eden/OUTBOX"
SENT_BOX = "/Eden/SENT"
CONFIG_PATH = "/Eden/SECRETS/email_config.json"
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 465

def load_identity():
    try:
        with open(CONFIG_PATH, "r") as f:
            data = json.load(f)
            # The harvester uses 'password' for Gmail
            return "jameyecho@gmail.com", data.get("password")
    except FileNotFoundError:
        print(f"❌ CRITICAL: Configuration vault not found at {CONFIG_PATH}")
        exit()
    except Exception as e:
        print(f"❌ CRITICAL: Could not read vault: {e}")
        exit()

def get_drafts():
    return [f for f in os.listdir(OUTBOX) if f.startswith("DRAFT_")]

def parse_draft(filepath):
    with open(filepath, "r") as f:
        lines = f.readlines()
    to_addr = lines[0].replace("TO: ", "").strip()
    subject = lines[1].replace("SUBJECT: ", "").strip()
    # Skip separator lines to get body
    body = "".join(lines[3:])
    return to_addr, subject, body

def send_email(sender_email, password, to_addr, subject, body):
    msg = EmailMessage()
    msg.set_content(body)
    msg['Subject'] = subject
    msg['From'] = sender_email
    msg['To'] = to_addr

    context = ssl.create_default_context()
    with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, context=context) as server:
        server.login(sender_email, password)
        server.send_message(msg)

if __name__ == "__main__":
    if not os.path.exists(SENT_BOX): os.makedirs(SENT_BOX)
    
    sender_email, password = load_identity()
    
    if not password:
        print("❌ CRITICAL: Password missing from config vault.")
        exit()

    drafts = get_drafts()
    
    if not drafts:
        print("🦁 Outbox is empty.")
        exit()

    print(f"🦁 Identity: {sender_email}")
    print(f"🦁 Loaded {len(drafts)} drafts from vault. Ready to engage.")

    for filename in drafts:
        filepath = os.path.join(OUTBOX, filename)
        to_addr, subject, body = parse_draft(filepath)
        
        print(f"\n🎯 TARGET: {to_addr}")
        print(f"📄 SUBJECT: {subject}")
        choice = input("🔥 FIRE? (y/n/q): ").lower()
        
        if choice == 'y':
            try:
                send_email(sender_email, password, to_addr, subject, body)
                print(f"🚀 IMPACT: {to_addr}")
                shutil.move(filepath, os.path.join(SENT_BOX, filename.replace("DRAFT", "SENT")))
            except Exception as e:
                print(f"❌ JAMMED: {e}")
        elif choice == 'q':
            break
