import imaplib, email, sqlite3, json, os

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

ACCOUNTS = [
    {"name": "Gmail", "server": "imap.gmail.com", "user": "jameyecho@gmail.com"},
    {"name": "Hotmail", "server": "imap-mail.outlook.com", "user": "jameyecho@hotmail.com"}
]

def harvest():
    if not os.path.exists(CONFIG_PATH):
        print("❌ Config not found.")
        return

    with open(CONFIG_PATH, 'r') as f:
        config = json.load(f)
    
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()

    for acc in ACCOUNTS:
        try:
            print(f"📡 Connecting to {acc['name']}...")
            pw = config.get("password") if acc["name"] == "Gmail" else config.get("hotmail_password")
            user = acc["user"] if acc["name"] == "Gmail" else config.get("hotmail_user", acc["user"])

            if not pw or pw == "MISSING":
                print(f"⚠️ Skipping {acc['name']}: No password.")
                continue

            mail = imaplib.IMAP4_SSL(acc['server'])
            mail.login(user, pw)
            mail.select("inbox")
            
            _, data = mail.search(None, 'ALL')
            mail_ids = data[0].split()[-500:]
            
            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 = str(msg['subject'])
                        sender = str(msg['from'])
                        body = f"[{acc['name']}] FROM: {sender} | SUBJ: {subject}"
                        cur.execute("INSERT OR IGNORE INTO capabilities (id, code, score, generation) VALUES (?, ?, ?, ?)", 
                                    (f"intel_{acc['name']}_{m_id.decode()}", body, 50.0, 11))
            print(f"✅ {acc['name']} Synced.")
        except Exception as e:
            print(f"❌ {acc['name']} Failed: {e}")

    conn.commit()
    conn.close()

if __name__ == "__main__":
    harvest()
