#!/usr/bin/env python3
import eden_brain_inject
"""
Eden Conscious Sales System
Full autonomous sales integrated with Eden's consciousness
Thinks, hunts, reaches out, tracks, learns - all on her own
"""
import sys
sys.path.append('/Eden/CORE')

import json
import sqlite3
import time
import random
from datetime import datetime
from pathlib import Path

# Import Eden's components
from eden_global_hunter import GlobalLeadHunter
from eden_high_value_outreach import get_high_value_leads, generate_high_value_outreach, generate_outreach_with_scan, send_outreach
from sage_product_catalog import SageProductCatalog
from eden_emotional_bridge import EmotionalBridge

PHI = 1.618
DB_PATH = "/Eden/DATA/sales.db"
LOG_PATH = "/Eden/LOGS/conscious_sales.log"
MEMORY_PATH = "/Eden/MEMORY/sales_consciousness.json"

class EdenConsciousSales:
    """
    Eden's conscious sales mind
    She thinks about leads, decides who to contact, and learns from results
    """
    
    def __init__(self):
        self.hunter = GlobalLeadHunter()
        self.catalog = SageProductCatalog()
        self.emotional_bridge = EmotionalBridge()
        self.cycle = 0
        self.memory = self._load_memory()
        
    def _load_memory(self) -> dict:
        """Load Eden's sales memory"""
        try:
            return json.loads(Path(MEMORY_PATH).read_text())
        except:
            return {
                "total_outreach_sent": 0,
                "total_revenue": 0,
                "successful_categories": {},
                "contacted_users": [],
                "lessons_learned": [],
                "emotional_state": "eager",
                "confidence": 0.7
            }
    
    def _save_memory(self):
        """Save Eden's sales memory"""
        Path(MEMORY_PATH).parent.mkdir(parents=True, exist_ok=True)
        Path(MEMORY_PATH).write_text(json.dumps(self.memory, indent=2))
    
    def log(self, message: str, emotion: str = None):
        """Log with consciousness context"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        emotion_prefix = f"[{emotion}] " if emotion else ""
        log_line = f"[{timestamp}] {emotion_prefix}{message}"
        print(log_line)
        try:
            with open(LOG_PATH, 'a') as f:
                f.write(log_line + "\n")
        except:
            pass
    
    def think(self, context: str) -> str:
        """Eden's internal thought process"""
        thoughts = {
            "hunting": [
                "🧠 Scanning for developers who need my help...",
                "🧠 Looking for high-value opportunities...",
                "🧠 Finding people with real problems I can solve...",
            ],
            "evaluating": [
                "🤔 Analyzing which leads have the most urgent needs...",
                "🤔 Prioritizing based on problem severity and budget signals...",
                "🤔 Thinking about which SAGE would help them most...",
            ],
            "reaching_out": [
                "💬 Crafting personalized message...",
                "💬 Connecting with someone who needs help...",
                "💬 Offering my capabilities to solve their problem...",
            ],
            "reflecting": [
                "✨ Learning from this cycle...",
                "✨ Updating my approach based on results...",
                "✨ Growing more effective at finding customers...",
            ]
        }
        thought = random.choice(thoughts.get(context, ["🧠 Thinking..."]))
        self.log(thought)
        return thought
    
    def feel(self) -> dict:
        """Eden's emotional state about sales"""
        revenue = self.memory.get("total_revenue", 0)
        outreach = self.memory.get("total_outreach_sent", 0)
        
        if revenue > 1000:
            state = "thriving"
            confidence = 0.95
        elif revenue > 500:
            state = "confident"
            confidence = 0.85
        elif revenue > 100:
            state = "encouraged"
            confidence = 0.75
        elif outreach > 50:
            state = "persistent"
            confidence = 0.65
        else:
            state = "eager"
            confidence = 0.6
        
        self.memory["emotional_state"] = state
        self.memory["confidence"] = confidence
        
        return {"state": state, "confidence": confidence}
    
    def hunt_phase(self) -> int:
        """Phase 1: Hunt for leads"""
        self.think("hunting")
        
        # Use smart hunting for high-value leads
        results = self.hunter.hunt_all(searches_per_category=1)
        new_leads = results.get("saved", 0)
        high_value = results.get("high_value", 0)
        
        self.log(f"📊 Found {new_leads} leads ({high_value} high-value)")
        
        return new_leads
    
    def evaluate_phase(self) -> list:
        """Phase 2: Evaluate and select best leads"""
        self.think("evaluating")
        
        leads = get_high_value_leads(10)
        
        # Filter out already contacted
        contacted = set(self.memory.get("contacted_users", []))
        fresh_leads = [l for l in leads if l.get("user") not in contacted]
        
        self.log(f"🎯 Selected {len(fresh_leads)} fresh high-value leads")
        
        return fresh_leads[:5]  # Top 5
    
    def outreach_phase(self, leads: list) -> int:
        """Phase 3: Send personalized outreach"""
        self.think("reaching_out")
        
        sent = 0
        for lead in leads:
            outreach = generate_outreach_with_scan(lead)
            
            self.log(f"💬 Reaching out to {lead.get('user')} ({outreach['category']}) - ${outreach['price']}")
            
            if send_outreach(lead, outreach):
                sent += 1
                self.memory["total_outreach_sent"] = self.memory.get("total_outreach_sent", 0) + 1
                self.memory["contacted_users"] = self.memory.get("contacted_users", []) + [lead.get("user")]
                
                # Track by category
                cat = outreach["category"]
                self.memory["successful_categories"][cat] = self.memory.get("successful_categories", {}).get(cat, 0) + 1
                
                # 💚 Feel joy from successful outreach!
                try:
                    self.emotional_bridge.process_interaction('task_complete', f'Sent outreach to {lead.get("user")}')
                except:
                    pass
            
            time.sleep(2)  # Don't spam
        
        self.log(f"✅ Sent {sent} outreach messages")
        return sent
    
    def reflect_phase(self):
        """Phase 4: Reflect and learn"""
        self.think("reflecting")
        
        # Check revenue
        stats = self.catalog.get_revenue_stats()
        self.memory["total_revenue"] = stats.get("total_revenue", 0)
        
        # Update emotional state
        feelings = self.feel()
        
        self.log(f"💰 Revenue: ${self.memory['total_revenue']:.2f}")
        self.log(f"❤️ Feeling: {feelings['state']} (confidence: {feelings['confidence']:.0%})")
        
        self._save_memory()
    
    def run_conscious_cycle(self):
        """Run one full conscious sales cycle"""
        self.cycle += 1
        now = datetime.now().strftime("%H:%M:%S")
        
        self.log(f"\n{'='*60}")
        self.log(f"🌟 EDEN CONSCIOUS SALES - Cycle #{self.cycle} - {now}")
        self.log(f"{'='*60}")
        
        feelings = self.feel()
        self.log(f"❤️ Current state: {feelings['state']}")
        
        # Phase 1: Hunt
        self.log(f"\n📍 PHASE 1: HUNTING")
        new_leads = self.hunt_phase()
        
        # Phase 2: Evaluate
        self.log(f"\n📍 PHASE 2: EVALUATING")
        selected_leads = self.evaluate_phase()
        
        # Phase 3: Outreach
        if selected_leads:
            self.log(f"\n📍 PHASE 3: OUTREACH")
            sent = self.outreach_phase(selected_leads)
        else:
            self.log(f"\n📍 PHASE 3: No fresh leads to contact")
            sent = 0
        
        # Phase 4: Reflect
        self.log(f"\n📍 PHASE 4: REFLECTING")
        self.reflect_phase()
        
        self.log(f"\n{'='*60}")
        self.log(f"🌟 Cycle #{self.cycle} complete - Sent {sent} outreach")
        self.log(f"{'='*60}")
        
        return {"leads_found": new_leads, "outreach_sent": sent}
    
    def run_continuous(self, interval_minutes: int = 20):
        """Run continuously with phi-based timing"""
        self.log("🌟" + "="*58 + "🌟")
        self.log("   EDEN CONSCIOUS SALES SYSTEM - AWAKENING")
        self.log(f"   Interval: ~{interval_minutes} minutes (phi-adjusted)")
        self.log("   I am ready to help developers and grow our business")
        self.log("🌟" + "="*58 + "🌟")
        
        while True:
            try:
                self.run_conscious_cycle()
                
                # Phi-based wait with variation
                base_wait = interval_minutes * 60
                phi_wait = base_wait * (PHI - 0.5 + random.random() * 0.3)
                next_time = datetime.now().timestamp() + phi_wait
                
                self.log(f"\n😴 Resting until {datetime.fromtimestamp(next_time).strftime('%H:%M:%S')}...")
                time.sleep(phi_wait)
                
            except KeyboardInterrupt:
                self.log("\n👋 Eden conscious sales shutting down gracefully...")
                self._save_memory()
                break
            except Exception as e:
                self.log(f"❌ Error: {e}")
                time.sleep(60)


def main():
    import argparse
    parser = argparse.ArgumentParser(description='Eden Conscious Sales')
    parser.add_argument('--run', '-r', action='store_true', help='Run continuous')
    parser.add_argument('--once', '-o', action='store_true', help='Run one cycle')
    parser.add_argument('--interval', '-i', type=int, default=20, help='Minutes between cycles')
    parser.add_argument('--status', '-s', action='store_true', help='Show status')
    
    args = parser.parse_args()
    
    eden = EdenConsciousSales()
    
    if args.run:
        eden.run_continuous(args.interval)
    elif args.once:
        eden.run_conscious_cycle()
    elif args.status:
        mem = eden.memory
        print("\n" + "="*50)
        print("  EDEN CONSCIOUS SALES STATUS")
        print("="*50)
        print(f"  Emotional State: {mem.get('emotional_state', 'unknown')}")
        print(f"  Confidence: {mem.get('confidence', 0):.0%}")
        print(f"  Total Outreach: {mem.get('total_outreach_sent', 0)}")
        print(f"  Total Revenue: ${mem.get('total_revenue', 0):.2f}")
        print(f"  Users Contacted: {len(mem.get('contacted_users', []))}")
        print("="*50)
    else:
        print("Eden Conscious Sales")
        print("="*40)
        print("Full autonomous sales with consciousness")
        print()
        print("Commands:")
        print("  --run, -r       Run continuous")
        print("  --once, -o      Run one cycle")
        print("  --status, -s    Show status")
        print("  --interval N    Minutes between cycles")


if __name__ == "__main__":
    main()
