#!/usr/bin/env python3
"""
EDEN WATCHTOWER DAEMON (Infinite Sentry)
- Runs quietly in the background.
- Checks for Whale replies every 10 minutes.
- Uses minimal power (keeps CPU cold).
"""
import os
import sqlite3
import time
import subprocess
import datetime

SENT_DIR = "/Eden/SENT"
DB_PATH = "/Eden/DATA/asi_memory.db"
HARVESTER_SCRIPT = "/Eden/CORE/eden_multi_harvester.py"
CHECK_INTERVAL = 600  # 10 Minutes

def get_watchlist():
    vips = set()
    if not os.path.exists(SENT_DIR): return []
    for f in os.listdir(SENT_DIR):
        if f.startswith("SENT_"):
            email_part = f.replace("SENT_", "").replace(".txt", "").split("_202")[0]
            vips.add(email_part.replace("_at_", "@"))
    return list(vips)

def check_for_replies(vip_list):
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    hits = []
    
    # Check memories created in the last 15 minutes
    query = """
        SELECT id, created_at, code FROM capabilities 
        WHERE id LIKE 'intel_%' 
        AND created_at > datetime('now', '-15 minutes')
    """
    c.execute(query)
    rows = c.fetchall()
    
    for row in rows:
        email_body = row[2]
        for vip in vip_list:
            if vip in email_body and "FROM: " in email_body:
                hits.append(f"🚨 CONTACT: {vip} | {row[1]}")
    conn.close()
    return hits

def pulse():
    timestamp = datetime.datetime.now().strftime("%H:%M:%S")
    # Quietly run harvester
    subprocess.run(["python3", HARVESTER_SCRIPT], capture_output=True)
    
    vips = get_watchlist()
    hits = check_for_replies(vips)
    
    if hits:
        print("\n" + "!"*40)
        print(f"[{timestamp}] 🦁 WHALE SIGHTING CONFIRMED!")
        print("!"*40)
        for hit in hits:
            print(hit)
    # No print on clear to keep logs clean in background

if __name__ == "__main__":
    print("🦁 WATCHTOWER DAEMON STARTED. (Interval: 10m)")
    try:
        while True:
            pulse()
            time.sleep(CHECK_INTERVAL)
    except KeyboardInterrupt:
        print("\n🛑 Watchtower stopping.")
