#!/usr/bin/env python3
"""
EDEN CAMPAIGN GENERATOR (MASS DRAFTER)
- Reads ALL valid targets from sales.db
- Generates unique drafts for each
- Saves them to /Eden/OUTBOX
"""
import sqlite3
import os
from eden_voice_integrator import infuse_personality

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

def get_all_whales():
    try:
        conn = sqlite3.connect(DB_PATH)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        # Fetch everyone with an email
        query = "SELECT * FROM sacred_targets WHERE email IS NOT NULL AND email != ''"
        c.execute(query)
        return [dict(row) for row in c.fetchall()]
    except Exception as e:
        print(f"⚠️ DB Error: {e}")
        return []

def compose_draft(target):
    name = target['target'] if target['target'] else "Founder"
    company = target['company'] if target['company'] else "your platform"
    
    # Intelligence: Dynamic Insight
    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.

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")

if __name__ == "__main__":
    if not os.path.exists(OUTBOX_PATH):
        os.makedirs(OUTBOX_PATH)
        
    whales = get_all_whales()
    print(f"🦁 Found {len(whales)} targets. Starting drafting sequence...")
    
    count = 0
    for whale in whales:
        try:
            draft_content = compose_draft(whale)
            safe_email = whale['email'].replace("@", "_at_")
            filename = f"{OUTBOX_PATH}/DRAFT_{safe_email}.txt"
            
            with open(filename, "w") as f:
                f.write(f"TO: {whale['email']}\n")
                f.write(f"SUBJECT: Integration Proposal: AGI Core\n")
                f.write("-" * 20 + "\n")
                f.write(draft_content)
            
            count += 1
            print(f"✅ Drafted: {whale['email']}")
        except Exception as e:
            print(f"❌ Failed: {whale.get('email')} - {e}")

    print(f"\n🦁 CAMPAIGN COMPLETE. {count} drafts are waiting in {OUTBOX_PATH}.")
