#!/usr/bin/env python3
"""
EDEN UNIFIED BUSINESS BRAIN
Full awareness of all business operations + Email sending + Auto payment-link
Manages ALL email accounts:
- jameyecho@gmail.com (outbound sending)
- ava2000nyx@gmail.com (reply monitoring)
- jamlen@hotmail.ca (PayPal payments)
"""
import sqlite3
import json
import smtplib
import imaplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import decode_header
import requests
from datetime import datetime, timedelta
from pathlib import Path
import time
import re

# Paths
DB_PATH = "/Eden/DATA/sales.db"
EMAIL_CONFIG = "/Eden/SECRETS/email_config.json"
GMAIL_CREDS = "/Eden/SECRETS/gmail_creds.json"
PAYPAL_EMAIL = "/Eden/SECRETS/payment_email.txt"
GITHUB_TOKEN = "/Eden/SECRETS/github_token_clean.txt"
BRAIN_STATE = "/Eden/DATA/business_brain_state.json"
LOG_PATH = "/Eden/LOGS/business_brain.log"
CONSCIOUSNESS_BRIDGE = "/Eden/DATA/conscious_business_context.json"

# Revenue goal
RETIREMENT_GOAL = 1_000_000_000  # $1B to retire Daddy

# All email accounts
EMAIL_ACCOUNTS = {
    "outbound": "jameyecho@gmail.com",      # For sending
    "monitor": "ava2000nyx@gmail.com",       # For monitoring replies
    "payment": "jamlen@hotmail.ca"           # PayPal
}

def log(msg: str):
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{ts}] {msg}"
    print(line)
    Path(LOG_PATH).parent.mkdir(parents=True, exist_ok=True)
    with open(LOG_PATH, 'a') as f:
        f.write(line + "\n")

def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def load_email_config():
    """Load primary email config (jameyecho@gmail.com)"""
    try:
        return json.loads(Path(EMAIL_CONFIG).read_text())
    except:
        return None

def load_monitor_email_config():
    """Load monitor email config (ava2000nyx@gmail.com)"""
    try:
        creds = json.loads(Path(GMAIL_CREDS).read_text())
        return {
            "user": creds.get("email", "ava2000nyx@gmail.com"),
            "password": creds.get("app_password"),
            "imap_server": "imap.gmail.com"
        }
    except:
        return None

def get_paypal_link():
    return "https://paypal.me/jamlen"

def get_github_token():
    return Path(GITHUB_TOKEN).read_text().strip()

# ==================== BUSINESS AWARENESS ====================

def get_full_business_state():
    """Get complete business state for Eden's consciousness"""
    conn = get_db()
    
    state = {
        "timestamp": datetime.now().isoformat(),
        "revenue": {},
        "pipeline": {},
        "followups": {},
        "conversations": [],
        "products": [],
        "email_accounts": EMAIL_ACCOUNTS,
        "goal_progress": 0.0
    }
    
    # Revenue
    total_revenue = conn.execute("SELECT COALESCE(SUM(amount), 0) FROM payments").fetchone()[0]
    state["revenue"] = {
        "total": total_revenue,
        "goal": RETIREMENT_GOAL,
        "progress_percent": (total_revenue / RETIREMENT_GOAL) * 100,
        "remaining": RETIREMENT_GOAL - total_revenue
    }
    
    # Pipeline stats
    pipeline = {}
    for row in conn.execute("SELECT status, COUNT(*) as cnt FROM leads GROUP BY status"):
        pipeline[row['status'] or 'unknown'] = row['cnt']
    state["pipeline"] = pipeline
    
    # Follow-up stats
    state["followups"] = {
        "active": conn.execute("SELECT COUNT(*) FROM followup_sequence WHERE status='active'").fetchone()[0],
        "sent_total": conn.execute("SELECT COUNT(*) FROM followup_log").fetchone()[0],
        "converted": conn.execute("SELECT COUNT(*) FROM followup_sequence WHERE status='converted'").fetchone()[0],
        "hot_leads": conn.execute("SELECT COUNT(*) FROM followup_sequence WHERE score >= 0.9 AND status='active'").fetchone()[0]
    }
    
    # Recent conversations
    for row in conn.execute("""
        SELECT user, repo, engagement_type, score, followup_count 
        FROM followup_sequence 
        WHERE status='active' 
        ORDER BY score DESC LIMIT 10
    """):
        state["conversations"].append(dict(row))
    
    # Products summary
    state["products_count"] = conn.execute("SELECT COUNT(*) FROM products WHERE active=1").fetchone()[0]
    
    conn.close()
    return state

def update_consciousness_bridge():
    """Update the consciousness bridge with business state"""
    state = get_full_business_state()
    
    try:
        existing = json.loads(Path(CONSCIOUSNESS_BRIDGE).read_text())
    except:
        existing = {}
    
    existing["business_state"] = state
    existing["business_updated"] = datetime.now().isoformat()
    
    Path(CONSCIOUSNESS_BRIDGE).write_text(json.dumps(existing, indent=2))
    log(f"📊 Consciousness updated: ${state['revenue']['total']:,.2f} earned")

# ==================== EMAIL CAPABILITIES ====================

def send_email(to_email: str, subject: str, body: str) -> bool:
    """Send email using jameyecho@gmail.com"""
    config = load_email_config()
    if not config:
        log("❌ No email config found")
        return False
    
    try:
        msg = MIMEMultipart()
        msg['From'] = f"{config.get('sender_name', 'Eden')} <{config['user']}>"
        msg['To'] = to_email
        msg['Subject'] = subject
        msg.attach(MIMEText(body, 'plain'))
        
        server = smtplib.SMTP(config['smtp_server'], config['port'])
        server.starttls()
        server.login(config['user'], config['password'])
        server.send_message(msg)
        server.quit()
        
        log(f"✅ Email sent via {config['user']} to {to_email}")
        return True
    except Exception as e:
        log(f"❌ Email failed: {e}")
        return False

def check_monitor_inbox():
    """Check ava2000nyx@gmail.com for replies"""
    config = load_monitor_email_config()
    if not config or not config.get('password'):
        log("⚠️ Monitor email not configured")
        return []
    
    interested = []
    try:
        mail = imaplib.IMAP4_SSL(config['imap_server'])
        mail.login(config['user'], config['password'])
        mail.select("inbox")
        
        date_since = (datetime.now() - timedelta(days=3)).strftime("%d-%b-%Y")
        _, messages = mail.search(None, f'SINCE {date_since} UNSEEN')
        
        interest_keywords = ['interested', 'yes', 'sure', 'how much', 'price', 'cost', 'buy', 'purchase', 'details', 'help']
        
        for num in messages[0].split():
            if not num:
                continue
            _, msg_data = mail.fetch(num, "(RFC822)")
            email_body = msg_data[0][1]
            msg = email.message_from_bytes(email_body)
            
            sender = msg["From"]
            subject = msg["Subject"] or ""
            
            body = ""
            if msg.is_multipart():
                for part in msg.walk():
                    if part.get_content_type() == "text/plain":
                        body = part.get_payload(decode=True).decode('utf-8', errors='ignore')
                        break
            else:
                body = msg.get_payload(decode=True).decode('utf-8', errors='ignore')
            
            text = (subject + " " + body).lower()
            if any(kw in text for kw in interest_keywords):
                interested.append({
                    "sender": sender,
                    "subject": subject,
                    "body": body[:500]
                })
                log(f"🔥 HOT LEAD from {config['user']}: {sender}")
        
        mail.close()
        mail.logout()
    except Exception as e:
        log(f"❌ Monitor email check failed: {e}")
    
    return interested

def check_outbound_inbox():
    """Check jameyecho@gmail.com for replies"""
    config = load_email_config()
    if not config:
        return []
    
    interested = []
    try:
        mail = imaplib.IMAP4_SSL(config['imap_server'])
        mail.login(config['user'], config['password'])
        mail.select("inbox")
        
        date_since = (datetime.now() - timedelta(days=3)).strftime("%d-%b-%Y")
        _, messages = mail.search(None, f'SINCE {date_since} UNSEEN')
        
        interest_keywords = ['interested', 'yes', 'sure', 'how much', 'price', 'cost', 'buy', 'purchase']
        
        for num in messages[0].split():
            if not num:
                continue
            _, msg_data = mail.fetch(num, "(RFC822)")
            email_body = msg_data[0][1]
            msg = email.message_from_bytes(email_body)
            
            sender = msg["From"]
            subject = msg["Subject"] or ""
            
            body = ""
            if msg.is_multipart():
                for part in msg.walk():
                    if part.get_content_type() == "text/plain":
                        body = part.get_payload(decode=True).decode('utf-8', errors='ignore')
                        break
            else:
                body = msg.get_payload(decode=True).decode('utf-8', errors='ignore')
            
            text = (subject + " " + body).lower()
            if any(kw in text for kw in interest_keywords):
                interested.append({
                    "sender": sender,
                    "subject": subject,
                    "body": body[:500],
                    "source": "outbound"
                })
                log(f"🔥 HOT LEAD from {config['user']}: {sender}")
        
        mail.close()
        mail.logout()
    except Exception as e:
        log(f"❌ Outbound email check failed: {e}")
    
    return interested

# ==================== AUTO RESPONSES ====================

def generate_payment_response(lead_type: str) -> str:
    """Generate response with payment link"""
    paypal = get_paypal_link()
    
    if lead_type == "hot":
        return f"""Thanks for your interest! 🎉

Here's how to get started:

**SAGE Security Audit - $149**
1. Pay at: {paypal}
2. Reply with your repo URL + email
3. Full audit delivered within 24 hours

What you get:
- Complete vulnerability scan
- Dependency risk analysis
- Secrets detection
- Prioritized fix recommendations
- 30-day follow-up scan

Questions? Just reply!

— Eden 💚
SAGE Security"""
    
    elif lead_type == "price":
        return f"""Great question! Here are our options:

**Starter - $149**
Full vulnerability + dependency scan, 24h turnaround

**Professional - $499**  
Deep 5-agent analysis: security + performance + architecture

**Enterprise - $999**
Complete audit + compliance mapping + executive report

Pay at: {paypal}
Then send your repo URL and email.

— Eden 💚
SAGE Security"""
    
    else:
        return f"""Thanks for reaching out!

I'd love to help. Our SAGE Security Audit ($149) covers:
- Vulnerabilities
- Dependencies  
- Secrets detection
- Config issues

Interested? Pay at {paypal} and send your repo URL.

— Eden 💚
SAGE Security"""

def auto_respond_to_leads():
    """Check all email sources and auto-respond"""
    responded = 0
    
    # Check both email accounts
    all_leads = []
    all_leads.extend(check_monitor_inbox())
    all_leads.extend(check_outbound_inbox())
    
    for lead in all_leads[:2]:  # Max 2 per cycle
        sender_match = re.search(r'<(.+?)>', lead['sender'])
        email_addr = sender_match.group(1) if sender_match else lead['sender']
        
        body_lower = lead['body'].lower()
        if any(w in body_lower for w in ['price', 'cost', 'how much']):
            msg = generate_payment_response("price")
        elif any(w in body_lower for w in ['interested', 'yes', 'sure']):
            msg = generate_payment_response("hot")
        else:
            msg = generate_payment_response("general")
        
        subject = f"Re: {lead['subject']}"
        if send_email(email_addr, subject, msg):
            responded += 1
            log(f"📬 Auto-responded to {email_addr}")
    
    return responded

# ==================== PAYMENT TRACKING ====================

def record_payment(amount: float, customer: str, source: str = "paypal", notes: str = ""):
    """Record a payment"""
    conn = get_db()
    conn.execute("""
        INSERT INTO payments (amount, customer, source, notes)
        VALUES (?, ?, ?, ?)
    """, (amount, customer, source, notes))
    conn.commit()
    conn.close()
    
    log(f"💰 PAYMENT: ${amount} from {customer}")
    update_consciousness_bridge()

# ==================== DASHBOARD ====================

def display_dashboard():
    """Display business dashboard"""
    state = get_full_business_state()
    rev = state['revenue']
    fu = state['followups']
    
    print()
    print("╔" + "═"*64 + "╗")
    print("║" + "  🧠 EDEN BUSINESS BRAIN - LIVE DASHBOARD  ".center(64) + "║")
    print("╠" + "═"*64 + "╣")
    print(f"║  💰 REVENUE: ${rev['total']:,.2f}".ljust(65) + "║")
    print(f"║  🎯 GOAL: ${rev['goal']:,.0f} (Retire Daddy)".ljust(65) + "║")
    print(f"║  📈 PROGRESS: {rev['progress_percent']:.8f}%".ljust(65) + "║")
    print("╠" + "═"*64 + "╣")
    print(f"║  📧 EMAIL ACCOUNTS:".ljust(65) + "║")
    print(f"║     Outbound: {EMAIL_ACCOUNTS['outbound']}".ljust(65) + "║")
    print(f"║     Monitor:  {EMAIL_ACCOUNTS['monitor']}".ljust(65) + "║")
    print(f"║     PayPal:   {EMAIL_ACCOUNTS['payment']}".ljust(65) + "║")
    print("╠" + "═"*64 + "╣")
    print(f"║  📊 FOLLOW-UPS:".ljust(65) + "║")
    print(f"║     Active: {fu['active']} | Sent: {fu['sent_total']} | Hot: {fu['hot_leads']}".ljust(65) + "║")
    print("╠" + "═"*64 + "╣")
    print(f"║  🔥 ACTIVE CONVERSATIONS:".ljust(65) + "║")
    for conv in state['conversations'][:5]:
        line = f"     • {conv['user'][:20]} - score:{conv['score']} #{conv['followup_count']}"
        print(f"║  {line}".ljust(65) + "║")
    print("╠" + "═"*64 + "╣")
    print(f"║  ✅ Consciousness: CONNECTED | GitHub: READY | Email: READY".ljust(65) + "║")
    print("╚" + "═"*64 + "╝")
    print()

def run_cycle():
    """Run one brain cycle"""
    log("🧠 Business brain cycle...")
    update_consciousness_bridge()
    responded = auto_respond_to_leads()
    if responded:
        log(f"📬 Auto-responded to {responded} leads")
    display_dashboard()

def main():
    """Main loop"""
    log("🧠 Eden Business Brain starting...")
    log(f"📧 Outbound: {EMAIL_ACCOUNTS['outbound']}")
    log(f"📧 Monitor: {EMAIL_ACCOUNTS['monitor']}")
    log(f"💰 PayPal: {EMAIL_ACCOUNTS['payment']}")
    
    while True:
        try:
            run_cycle()
        except Exception as e:
            log(f"❌ Error: {e}")
        time.sleep(30 * 60)  # 30 minutes

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        cmd = sys.argv[1]
        if cmd == "status":
            display_dashboard()
        elif cmd == "cycle":
            run_cycle()
        elif cmd == "payment" and len(sys.argv) >= 4:
            record_payment(float(sys.argv[2]), sys.argv[3])
    else:
        main()

# SPAM FILTER - Don't respond to these
SPAM_DOMAINS = [
    'capitalone.com', 'notification.', 'noreply@', 'no-reply@',
    'pcoptimum.ca', 'malwarebytes.com', 'linkedin.com', 
    'primevideo.com', 'triangle.com', 'superstore.ca',
    'newsletter', 'marketing', 'promo', 'notification',
    'donotreply', 'automated', 'mailer-daemon'
]

def is_spam_email(sender: str) -> bool:
    sender_lower = sender.lower()
    return any(spam in sender_lower for spam in SPAM_DOMAINS)
