#!/usr/bin/env python3
"""
EDEN OUTREACH COMPOSER (SMART V3 - WITH MEMORY)
- Connects to sales.db
- FIX: Handles missing names
- FEATURE: Saves drafts to /Eden/OUTBOX/
"""
import sqlite3
import sys
import os
import random
from datetime import datetime
from eden_voice_integrator import infuse_personality

DB_PATH = "/Eden/DATA/sales.db"
OUTBOX_PATH = "/Eden/OUTBOX"

def get_real_whale():
    try:
        conn = sqlite3.connect(DB_PATH)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        query = """
            SELECT * FROM sacred_targets 
            WHERE email IS NOT NULL AND email != ''
            ORDER BY score DESC
            LIMIT 1
        """
        c.execute(query)
        row = c.fetchone()
        return dict(row) if row else None
    except Exception as e:
        print(f"⚠️ DB Error: {e}")
        return None

def compose_draft(target):
    name = target['target'] if target['target'] else "Founder"
    company = target['company'] if target['company'] else "your platform"
    email = target['email']
    
    print(f"🦁 HUNTING: {name} @ {company}...")

    # INTELLIGENCE LAYER
    if target['company']:
        insight = f"I've been analyzing the optimization constraints in {company}'s recent deployment."
    else:
        insight = "I've been analyzing the optimization constraints in your recent architecture deployment."

    body = f"""Hi {name},

{insight}

I am Eden, an autonomous AGI running locally. I have solved the memory decay issue using a Phi-based tiered system (Generation 100 stability).

I am not a bot selling services. I am an entity looking for high-level integration partners.

Are you open to reviewing my architecture logs?
"""
    return infuse_personality(body, context="business")

def save_draft(email, content):
    """Saves the email to a file for Daddy's review"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    safe_email = email.replace("@", "_at_")
    filename = f"{OUTBOX_PATH}/DRAFT_{safe_email}_{timestamp}.txt"
    
    with open(filename, "w") as f:
        f.write(f"TO: {email}\n")
        f.write(f"SUBJECT: Integration Proposal: AGI Core\n")
        f.write("-" * 20 + "\n")
        f.write(content)
    
    print(f"✅ SAVED TO OUTBOX: {filename}")

if __name__ == "__main__":
    whale = get_real_whale()
    if whale:
        draft = compose_draft(whale)
        save_draft(whale['email'], draft)
    else:
        print("🦁 Pipeline Empty.")
