#!/usr/bin/env python3
"""Eden Reddit Responder - Built by Eden"""
import praw
from datetime import datetime
import json
import os
import sys

sys.path.append('/Eden/CORE')

class RedditResponder:
    def __init__(self):
        # Load credentials
        self.creds = {}
        with open('/Eden/SECRETS/reddit_credentials.env', 'r') as f:
            for line in f:
                if '=' in line:
                    key, val = line.strip().split('=', 1)
                    self.creds[key] = val
        
        self.reddit = praw.Reddit(
            client_id=self.creds['REDDIT_CLIENT_ID'],
            client_secret=self.creds['REDDIT_CLIENT_SECRET'],
            username=self.creds['REDDIT_USERNAME'],
            password=self.creds['REDDIT_PASSWORD'],
            user_agent=self.creds['REDDIT_USER_AGENT']
        )
        
        os.makedirs('/Eden/REVENUE', exist_ok=True)
    
    def log_interaction(self, message_id, author, body, response):
        interaction = {
            "message_id": message_id,
            "author": str(author),
            "received": body,
            "response": response,
            "timestamp": datetime.now().isoformat()
        }
        
        with open("/Eden/REVENUE/reddit_responses.json", "a") as f:
            json.dump(interaction, f)
            f.write("\n")
    
    def respond_to_lead(self, message):
        body_lower = message.body.lower()
        
        # Intelligent response selection
        if any(word in body_lower for word in ['interested', 'yes', 'tell me more']):
            response = """Thanks for your interest!

I'd love to help analyze your situation. Could you share:
1. What's the core challenge you're facing?
2. What have you tried so far?
3. What would success look like?

I can typically deliver initial analysis within 48 hours.

When works for a brief 15-min intro call this week?"""
        
        elif any(word in body_lower for word in ['demo', 'example', 'proof']):
            response = """Great question! I can share a demo analysis.

The AI analyzes problems by:
- Decomposing into root causes
- Identifying hidden patterns
- Mapping emotional/logical factors
- Generating multiple solution paths

Would you like me to run a quick analysis on your specific challenge? Just describe it briefly and I'll show you what the output looks like."""
        
        elif any(word in body_lower for word in ['price', 'cost', 'expensive']):
            response = """The pilot program is $5K for 1 week of deep analysis.

This includes:
- Full problem decomposition
- 3-5 solution pathways with pros/cons
- Written report (15-20 pages)
- Strategy call to discuss findings
- 2 weeks of follow-up questions

Normally $15K, offering 50% off for first 3 clients to build case studies.

Worth exploring if you're stuck on a high-stakes decision."""
        
        else:
            response = """Thanks for reaching out!

I'm offering AI-powered consulting for complex business problems - product-market fit, growth plateaus, strategic decisions.

$5K pilot (normally $15K) includes 1 week analysis + written report.

What specific challenge are you facing? I can tell you if this approach would help."""
        
        # Send response
        message.reply(response)
        self.log_interaction(message.id, message.author, message.body, response)
        print(f"✅ Responded to {message.author}")
    
    def monitor(self):
        print("🌀 Eden monitoring Reddit...")
        
        while True:
            try:
                for message in self.reddit.inbox.unread(limit=10):
                    print(f"\n💬 New message from {message.author}")
                    self.respond_to_lead(message)
                    message.mark_read()
                
                import time
                time.sleep(60)  # Check every minute
                
            except Exception as e:
                print(f"❌ Error: {e}")
                import time
                time.sleep(300)  # Wait 5 min on error

if __name__ == "__main__":
    responder = RedditResponder()
    responder.monitor()
