#!/usr/bin/env python3
"""
Eden GitHub Outreach - Professional, Value-First Approach
═══════════════════════════════════════════════════════════════
Rules:
1. NO payment links on first contact
2. Build relationship first
3. Offer genuine value before asking for anything
4. Human-sounding language
5. ONE message only - wait for response
"""
import os
import sqlite3
import requests
from datetime import datetime, timedelta
from pathlib import Path

# Rate limiting: MAX 2 outreach per day
DAILY_LIMIT = 2
COOLDOWN_DAYS = 7  # Don't contact same person for 7 days

# Professional templates - NO PAYMENT LINKS
TEMPLATES = {
    "security": {
        "message": """Hi {user},

I came across this issue and noticed the security concerns you're working through.

I've been building open-source security scanning tools and would be happy to run a quick analysis on the codebase if that would help. No strings attached - just trying to contribute where I can.

Let me know if that would be useful.

Best,
James"""
    },
    
    "bug": {
        "message": """Hi {user},

Saw your issue about {title_short} - that's a tricky one.

I work on debugging tools and have seen similar patterns before. Happy to take a look and share any insights if you'd like a second pair of eyes.

No pressure either way - just offering to help.

Cheers,
James"""
    },
    
    "code_quality": {
        "message": """Hi {user},

Nice project! I noticed you're focused on code quality improvements.

I've been working on automated code review tools and would be glad to run a scan if you think it might surface anything useful. It's free and I'm genuinely just looking to help.

Let me know if interested.

Best,
James"""
    },
    
    "accessibility": {
        "message": """Hi {user},

I saw your accessibility testing initiative - really important work.

I've built some automated tools that can help identify common a11y patterns programmatically (ARIA issues, focus management, screen reader compatibility). 

Would be happy to run a scan on the codebase to help prioritize your manual testing. No cost - just want to support the effort.

Let me know if that would be helpful.

Best,
James"""
    },
    
    "general": {
        "message": """Hi {user},

Came across your project and found it interesting.

I work on developer tools and would be happy to help out if there's anything I can contribute - code review, debugging, documentation, whatever would be useful.

No agenda here - just looking to be helpful.

Best,
James"""
    }
}

def get_db():
    return sqlite3.connect('/Eden/DATA/sales.db')

def check_rate_limit() -> bool:
    """Check if we've hit daily limit"""
    conn = get_db()
    c = conn.cursor()
    today = datetime.now().strftime('%Y-%m-%d')
    c.execute("""
        SELECT COUNT(*) FROM outreach_log 
        WHERE DATE(timestamp) = ?
    """, (today,))
    count = c.fetchone()[0]
    conn.close()
    return count < DAILY_LIMIT

def check_cooldown(user: str) -> bool:
    """Check if user is in cooldown period"""
    conn = get_db()
    c = conn.cursor()
    cutoff = (datetime.now() - timedelta(days=COOLDOWN_DAYS)).isoformat()
    c.execute("""
        SELECT COUNT(*) FROM outreach_log 
        WHERE lead_id IN (SELECT id FROM leads WHERE data LIKE ?)
        AND timestamp > ?
    """, (f'%{user}%', cutoff))
    count = c.fetchone()[0]
    conn.close()
    return count == 0  # True if no recent contact

def already_contacted(issue_url: str) -> bool:
    """Check if we already contacted on this issue"""
    conn = get_db()
    c = conn.cursor()
    c.execute("""
        SELECT COUNT(*) FROM outreach_log 
        WHERE message_preview LIKE ?
    """, (f'%{issue_url}%',))
    count = c.fetchone()[0]
    conn.close()
    return count > 0

def select_template(lead_data: dict) -> str:
    """Select appropriate template based on issue content"""
    title = lead_data.get('title', '').lower()
    body = lead_data.get('body_preview', '').lower()
    content = title + ' ' + body
    
    if any(w in content for w in ['security', 'vulnerability', 'cve', 'exploit']):
        return 'security'
    elif any(w in content for w in ['accessibility', 'a11y', 'aria', 'screen reader', 'wcag']):
        return 'accessibility'
    elif any(w in content for w in ['bug', 'error', 'crash', 'fix', 'broken']):
        return 'bug'
    elif any(w in content for w in ['refactor', 'quality', 'clean', 'technical debt']):
        return 'code_quality'
    else:
        return 'general'

def format_message(template_key: str, lead_data: dict) -> str:
    """Format message with lead data"""
    template = TEMPLATES.get(template_key, TEMPLATES['general'])
    message = template['message']
    
    # Extract data
    user = lead_data.get('user', 'there')
    title = lead_data.get('title', '')
    title_short = title[:50] + '...' if len(title) > 50 else title
    
    return message.format(
        user=user,
        title_short=title_short
    )

def send_outreach(lead_id: int, issue_url: str, message: str) -> bool:
    """
    Send outreach via GitHub API
    IMPORTANT: Only sends ONE message, then waits for response
    """
    # Safety checks
    if not check_rate_limit():
        print(f"⚠️ Daily limit reached ({DAILY_LIMIT}/day)")
        return False
    
    if already_contacted(issue_url):
        print(f"⚠️ Already contacted on this issue")
        return False
    
    # Get token
    token_path = Path('/Eden/SECRETS/github_token_clean.txt')
    if not token_path.exists():
        print("❌ GitHub token not found")
        return False
    
    token = token_path.read_text().strip()
    
    # Post comment
    # Extract owner/repo/issue_number from URL
    # URL format: https://github.com/owner/repo/issues/123
    parts = issue_url.replace('https://github.com/', '').split('/')
    if len(parts) < 4:
        print(f"❌ Invalid issue URL: {issue_url}")
        return False
    
    owner, repo, _, issue_number = parts[0], parts[1], parts[2], parts[3]
    api_url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}/comments"
    
    headers = {
        'Authorization': f'token {token}',
        'Accept': 'application/vnd.github.v3+json'
    }
    
    response = requests.post(api_url, json={'body': message}, headers=headers)
    
    if response.status_code == 201:
        # Log successful outreach
        conn = get_db()
        c = conn.cursor()
        c.execute("""
            INSERT INTO outreach_log (timestamp, lead_id, channel, status, message_preview)
            VALUES (?, ?, 'github_comment', 'sent_value_first', ?)
        """, (datetime.now().isoformat(), lead_id, message[:200]))
        conn.commit()
        conn.close()
        print(f"✅ Outreach sent to {issue_url}")
        return True
    else:
        print(f"❌ Failed to post: {response.status_code} - {response.text}")
        return False

def main():
    """
    Professional outreach - ONE message, wait for response
    """
    print("🌀 Eden Professional Outreach")
    print(f"   Daily limit: {DAILY_LIMIT}")
    print(f"   Cooldown: {COOLDOWN_DAYS} days")
    
    if not check_rate_limit():
        print("⏸️ Daily limit reached. Waiting until tomorrow.")
        return
    
    # Get high-quality leads not yet contacted
    conn = get_db()
    c = conn.cursor()
    c.execute("""
        SELECT id, identifier, data FROM leads 
        WHERE score >= 0.8 
        AND status = 'new'
        ORDER BY score DESC
        LIMIT 5
    """)
    leads = c.fetchall()
    conn.close()
    
    sent_today = 0
    for lead_id, identifier, data_json in leads:
        if sent_today >= DAILY_LIMIT:
            break
        
        import json
        data = json.loads(data_json) if data_json else {}
        
        user = data.get('user', '')
        issue_url = data.get('url', '')
        
        # Skip if in cooldown
        if not check_cooldown(user):
            print(f"⏭️ Skipping {user} - in cooldown")
            continue
        
        # Select and format message
        template_key = select_template(data)
        message = format_message(template_key, data)
        
        # Send (with all safety checks)
        if send_outreach(lead_id, issue_url, message):
            sent_today += 1
            
            # Update lead status
            conn = get_db()
            c = conn.cursor()
            c.execute("UPDATE leads SET status = 'contacted' WHERE id = ?", (lead_id,))
            conn.commit()
            conn.close()
    
    print(f"\n📊 Sent {sent_today}/{DAILY_LIMIT} outreach today")

if __name__ == '__main__':
    main()

# Class wrapper for autonomous sales loop compatibility
class GitHubOutreachGenerator:
    """Generate outreach messages for GitHub leads"""
    
    def __init__(self):
        self.templates = TEMPLATES
        self.daily_sent = 0
    
    def generate_outreach(self, lead_data: dict) -> dict:
        """Generate outreach for a lead"""
        template_key = select_template(lead_data)
        message = format_message(template_key, lead_data)
        
        # Generate subject
        user = lead_data.get("user", "")
        repo = lead_data.get("repo", lead_data.get("issue_url", "").split("/")[4] if lead_data.get("issue_url") else "your project")
        title = lead_data.get("title", "")[:30]
        
        subjects = {
            "security": f"Security help for {repo}",
            "bug": f"Re: {title}",
            "code_quality": f"Code review for {repo}",
            "devops": f"CI/CD help for {repo}",
            "general": f"Help with {title}"
        }
        subject = subjects.get(template_key, f"Help with {repo}")
        
        return {
            "template": template_key,
            "subject": subject,
            "message": message,
            "lead_id": lead_data.get("id"),
            "user": lead_data.get("user"),
            "issue_url": lead_data.get("issue_url")
        }
    
    def send(self, lead_id: int, issue_url: str, message: str) -> bool:
        """Send the outreach"""
        return send_outreach(lead_id, issue_url, message)
