import imaplib, email, sqlite3, json, os
from pathlib import Path

DB_PATH = "/Eden/DATA/asi_memory.db"
CONFIG_PATH = "/Eden/SECRETS/email_config.json"

def harvest():
    if not os.path.exists(CONFIG_PATH):
        print("❌ Error: /Eden/SECRETS/email_config.json not found.")
        return

    with open(CONFIG_PATH, 'r') as f:
        config = json.load(f)
    
    if config["password"] == "NEED_APP_PASSWORD":
        print("❌ Error: You haven't updated the App Password in /Eden/SECRETS/email_config.json yet.")
        return

    # Connect to Gmail (Primary Business)
    try:
        mail = imaplib.IMAP4_SSL("imap.gmail.com")
        mail.login(config["user"], config["password"])
        mail.select("inbox")
        
        # Search for last 50 emails
        _, data = mail.search(None, 'ALL')
        mail_ids = data[0].split()[-50:]
        
        conn = sqlite3.connect(DB_PATH)
        cur = conn.cursor()
        
        print(f"📥 Syncing {len(mail_ids)} emails to Eden Memory...")
        for m_id in mail_ids:
            _, msg_data = mail.fetch(m_id, '(RFC822)')
            for response_part in msg_data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_bytes(response_part[1])
                    subject = msg['subject']
                    sender = msg['from']
                    # Inject into capabilities with a high 'Growth' score
                    body = f"FROM: {sender} | SUBJ: {subject}"
                    cur.execute("INSERT OR IGNORE INTO capabilities (id, code, score, generation) VALUES (?, ?, ?, ?)", 
                                (f"email_{m_id.decode()}", body, 50.0, 11))
        
        conn.commit()
        conn.close()
        print("✅ Eden is now synced with jameyecho@gmail.com")
    except Exception as e:
        print(f"❌ Connection failed: {e}")

if __name__ == "__main__":
    harvest()
