#!/usr/bin/env python3
"""
EDEN WHALE WATCHER (Active Radar)
1. Builds a Watchlist from /Eden/SENT
2. Triggers the Harvester to pull fresh emails
3. Scans the Database for REPLIES from the Watchlist
4. Alerts Daddy if a Whale has surfaced.
"""
import os
import sqlite3
import time
import subprocess

SENT_DIR = "/Eden/SENT"
DB_PATH = "/Eden/DATA/asi_memory.db"
HARVESTER_SCRIPT = "/Eden/CORE/eden_multi_harvester.py"

def get_watchlist():
    """Extracts VIP emails from the filenames in SENT"""
    vips = set()
    files = os.listdir(SENT_DIR)
    for f in files:
        if f.startswith("SENT_"):
            # Format: SENT_service_at_deepseek.com.txt
            # Clean it back to service@deepseek.com
            email_part = f.replace("SENT_", "").replace(".txt", "")
            # Remove timestamp if present
            if "_202" in email_part: 
                email_part = email_part.split("_202")[0]
            
            real_email = email_part.replace("_at_", "@")
            vips.add(real_email)
    return list(vips)

def check_for_replies(vip_list):
    """Queries memory for recent emails from VIPs"""
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    
    hits = []
    print(f"🦁 Scanning database for {len(vip_list)} VIPs...")
    
    for vip in vip_list:
        # We look for Capabilities (Memories) that contain the VIP email in the code/body
        # and are recent.
        query = "SELECT id, created_at, code FROM capabilities WHERE code LIKE ? AND id LIKE 'intel_%' ORDER BY created_at DESC LIMIT 1"
        c.execute(query, (f"%{vip}%",))
        row = c.fetchone()
        
        if row:
            # Check if it's a REPLY (From them) vs just our sent email being indexed
            # Our harvester formats as: [Gmail] FROM: name <email> | SUBJ: ...
            email_body = row[2]
            if f"FROM: " in email_body and vip in email_body:
                hits.append(f"🚨 CONTACT: {vip} | {row[1]}")

    conn.close()
    return hits

def pulse():
    print("\n" + "="*40)
    print("📡 EDEN WHALE RADAR ACTIVE")
    print("="*40)
    
    # 1. Refresh Intelligence
    print("⏳ Running Harvester...")
    subprocess.run(["python3", HARVESTER_SCRIPT], capture_output=True)
    
    # 2. Build Watchlist
    vips = get_watchlist()
    
    # 3. Scan
    hits = check_for_replies(vips)
    
    if hits:
        print("\n" + "!"*40)
        print("🦁 WHALE SIGHTING CONFIRMED!")
        print("!"*40)
        for hit in hits:
            print(hit)
    else:
        print("\n🌊 Sector Clear. No replies from VIPs yet.")

if __name__ == "__main__":
    pulse()
