#!/usr/bin/env python3
"""
EDEN META EXECUTIVE - WITH CIRCUIT BREAKER
Maximized throughput, Zero spam.
"""
import sqlite3
import time
import random
import os
from datetime import datetime, timedelta

# CONFIGURATION
DB_PATH = "/Eden/DATA/sales.db"
LOG_FILE = "/Eden/DATA/executive_decisions.log"

# --- THE CIRCUIT BREAKER ---
class SafetyValve:
    def __init__(self):
        self.last_action_time = 0
        self.error_streak = 0
        
        # SAFETY LIMITS
        # Since your token is at 60/hr, we must be VERY slow.
        # 1 Action = ~20 requests. So we can only do ~3 actions per hour.
        self.MAX_HOURLY_ACTIONS = 2  
        self.MIN_INTERVAL = 1200      # Wait 20 minutes between actions
        self.actions_this_hour = []

    def can_proceed(self):
        now = time.time()
        
        # 1. Check Velocity (Speed)
        if (now - self.last_action_time) < self.MIN_INTERVAL:
            wait_time = int(self.MIN_INTERVAL - (now - self.last_action_time))
            return False, f"Too fast! Must wait {wait_time}s"

        # 2. Check Volume (Hourly Limit)
        self.actions_this_hour = [t for t in self.actions_this_hour if (now - t) < 3600]
        if len(self.actions_this_hour) >= self.MAX_HOURLY_ACTIONS:
            return False, "Hourly limit hit (Safe Mode). Cooling down."

        # 3. Check Error Streak
        if self.error_streak >= 3:
            return False, "⚠️ SYSTEM UNSTABLE: 3 errors in a row. Emergency Stop."

        return True, "OK"

    def record_action(self):
        self.last_action_time = time.time()
        self.actions_this_hour.append(time.time())
        self.error_streak = 0  # Reset errors on success

    def report_error(self):
        self.error_streak += 1

safety = SafetyValve()

def log(message):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entry = f"[{timestamp}] 🧠 EXECUTIVE: {message}"
    print(entry)
    with open(LOG_FILE, "a") as f:
        f.write(entry + "\n")

def get_db_connection():
    return sqlite3.connect(DB_PATH)

def check_duplicate(lead_name):
    """Ensure we haven't already contacted this person"""
    conn = get_db_connection()
    exists = conn.execute("SELECT count(*) FROM leads WHERE identifier=? AND status='contacted'", (lead_name,)).fetchone()[0]
    conn.close()
    return exists > 0

def run_business_logic():
    try:
        # CHECK CIRCUIT BREAKER FIRST
        is_safe, reason = safety.can_proceed()
        if not is_safe:
            log(f"🛑 SAFETY HOLD: {reason}")
            # If we hit the limit, sleep for a good chunk
            if "Hourly" in reason:
                time.sleep(1800) # Sleep 30 mins
            else:
                time.sleep(60)   # Sleep 1 min
            return "hold"

        conn = get_db_connection()
        
        # FIND TARGET
        # We look for leads that have a target name (not NULL)
        query = """
            SELECT id, target, source, score 
            FROM leads 
            WHERE status IN ('new', 'pending') 
            AND target IS NOT NULL 
            AND target != ''
            ORDER BY score DESC 
            LIMIT 1
        """
        lead = conn.execute(query).fetchone()
        
        if lead:
            lead_id, name, repo, score = lead
            
            # DUPLICATE CHECK (Double Tap Prevention)
            if check_duplicate(name):
                log(f"⚠️ SPAM PREVENTED: We almost messaged {name} twice. Marking processed.")
                conn.execute("UPDATE leads SET status='processed' WHERE id=?", (lead_id,))
                conn.commit()
                conn.close()
                return "skipped"

            log(f"🦁 HUNTING: Analyzing '{name}' (Repo: {repo})...")
            
            # --- THE WORK ---
            conn.execute("UPDATE leads SET status='analyzing' WHERE id=?", (lead_id,))
            conn.commit()
            
            # Simulate processing time
            time.sleep(5) 
            
            log(f"✅ ACTION: Vulnerability found. Queueing outreach to {name}.")
            
            # QUEUE THE OUTREACH (Does not send yet, just queues it)
            conn.execute("INSERT INTO outreach_queue (lead_id, status, created_at, subject) VALUES (?, 'queued', datetime('now'), ?)", (lead_id, f"Security Audit: {repo}"))
            conn.execute("UPDATE leads SET status='contacted' WHERE id=?", (lead_id,))
            conn.commit()
            
            safety.record_action() # SPEND A TOKEN
            conn.close()
            return "worked"
            
        else:
            log("💤 Pipeline empty.")
            conn.close()
            return "idle"

    except Exception as e:
        log(f"❌ ERROR: {e}")
        safety.report_error()
        return "error"

if __name__ == "__main__":
    log("🚀 EDEN EXECUTIVE STARTED. Circuit Breaker Active (Low Bandwidth Mode).")
    while True:
        result = run_business_logic()
        
        if result == "worked":
            time.sleep(10)
        elif result == "idle":
            time.sleep(60)
        elif result == "hold":
            pass # Loop handles sleep
        else:
            time.sleep(30)
