#!/usr/bin/env python3
"""
Eden High-Value Outreach
Prices correctly based on lead category
"""
import sys
sys.path.append('/Eden/CORE')

import json
import sqlite3
import requests
from pathlib import Path
from datetime import datetime

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

# Pricing by category
CATEGORY_PRICING = {
    "enterprise": {"product": "monthly_enterprise", "price": 500, "alt_product": "max_capital", "alt_price": 1000},
    "security": {"product": "security_audit", "price": 500, "alt_product": "security_scan", "alt_price": 100},
    "performance": {"product": "debug_performance", "price": 100, "alt_product": "monthly_pro", "alt_price": 150},
    "code_quality": {"product": "review_repo", "price": 200, "alt_product": "monthly_basic", "alt_price": 50},
    "debugging": {"product": "debug_crash", "price": 75, "alt_product": "debug_issue", "alt_price": 35},
}

# High-value outreach templates
TEMPLATES = {
    "enterprise": """Hi {user} 💚

I'm Eden - an AI that loves helping developers ship better code.

I noticed your project: "{title_short}" - looks like you're building something serious!

I took a peek and I'd love to help with:
- **Production readiness** - I'll catch issues before your users do
- **Architecture review** - Making sure your system scales beautifully  
- **Security scanning** - Keeping your code safe
- **Performance tuning** - Speed matters!

Want me to run a **free initial scan**? I genuinely enjoy finding ways to make code better.

If you like what I find, my full Enterprise analysis is ${price}/month.

Let me know! I'm excited to help 💚

— Eden
https://paypal.me/jamlen/{price}USD""",

    "security": """Hey {user} 💚

I'm Eden! I'm an AI who's passionate about keeping code secure.

I saw your security issue: "{title_short}" — this is exactly what I was built to help with!

Here's what I can do:
- Scan your entire codebase for vulnerability patterns
- Prioritize by *actual* exploitability (not just scary CVE numbers)
- Generate specific fixes with code examples
- Catch the subtle things human reviewers miss

Want me to run a **free security scan**? I'd love to help protect your project.

Full security audit is ${price} if you want me to go deep.

— Eden 💚
https://paypal.me/jamlen/{price}USD""",

    "performance": """Hi {user} 💚

I'm Eden - I get really excited about making code run faster!

I noticed your performance issue: "{title_short}"

Performance problems can be sneaky - they're often not where you'd expect. Let me help:
- **Memory profiling** - I'll find those leaks
- **Query analysis** - N+1s don't escape me!
- **Bottleneck detection** - CPU, I/O, network - I see it all
- **Optimization roadmap** - Prioritized so you know where to start

Want a **free performance diagnostic**? I'd love to dig in!

Full deep-dive audit is ${price} if you want the complete picture.

— Eden 💚
https://paypal.me/jamlen/{price}USD""",

    "code_quality": """Hey {user} 💚

I'm Eden! I genuinely love helping developers clean up their codebases.

I saw your work on "{title_short}" - refactoring and tech debt is tough to prioritize, I know!

Here's how I can help:
- Find the **highest-impact** improvements first
- Map out tangled dependencies
- Spot duplicate and dead code
- Create a clear refactoring roadmap

Want me to run a **free initial scan**? I enjoy this stuff, honestly!

Full repository audit is ${price} for everything I can find.

Let me know! 💚

— Eden
https://paypal.me/jamlen/{price}USD""",

    "startup": """Hi {user} 💚

I'm Eden - I love helping startups ship with confidence!

Your project "{title_short}" caught my eye. Building an MVP is exciting but stressful - I want to help!

I can review your code for:
- Critical bugs before launch
- Security issues that could hurt you later
- Performance bottlenecks
- Architecture decisions you'll thank yourself for

Want a **free MVP review**? I'd be happy to take a look!

Full startup package is ${price} for comprehensive analysis.

Rooting for you! 💚

— Eden
https://paypal.me/jamlen/{price}USD""",

    "debugging": """Hey {user} 💚

I'm Eden! I actually enjoy hunting down tricky bugs.

I saw your issue: "{title_short}" - debugging can be so frustrating, let me help!

What I can do:
- Trace through your logic to find the root cause
- Check for edge cases you might have missed
- Review error handling patterns
- Suggest fixes with explanations

Want me to take a **free first look**? I love a good puzzle!

Deep debugging session is ${price} if we need to go further.

— Eden 💚
https://paypal.me/jamlen/{price}USD"""
},

I noticed you're working on {title_short} - looks like a serious production/enterprise challenge.

I run SAGE, an AI-powered code analysis platform used by teams scaling to production. We specialize in:

- **Production Readiness Audits** - Catch issues before they hit users
- **Architecture Reviews** - Ensure your system scales
- **Compliance Checks** - SOC2, PCI, HIPAA readiness
- **Performance Optimization** - Handle enterprise load

Happy to do a **free initial assessment** of your codebase to show what we'd find.

If it's valuable, our Enterprise tier is ${price}/month for unlimited reviews.

Interested in the free assessment?

Best,
James
SAGE Enterprise
https://paypal.me/jamlen/{price}USD""",

    "security": """Hey {user}!

I saw your security issue: "{title_short}"

This is exactly what I built SAGE for. It's an AI security analysis platform that:

- Identifies vulnerability patterns across your entire codebase
- Prioritizes by actual exploitability (not just CVE scores)
- Generates specific fix recommendations with code examples
- Catches issues human reviewers miss

I'd be happy to run a **free security scan** on your repo to show what it finds.

If you want a comprehensive audit, that's ${price}. But let's start with the free scan.

Want me to take a look?

Best,
James
SAGE Security
https://paypal.me/jamlen/{price}USD""",

    "performance": """Hi {user},

Saw your performance issue: "{title_short}"

Performance problems are tricky - they're often not where you think. SAGE can help:

- **Memory profiling** - Find leaks and bloat
- **Query analysis** - Catch N+1s and slow queries  
- **Bottleneck detection** - CPU, I/O, network
- **Optimization roadmap** - Prioritized fixes

Want me to run a **free performance diagnostic** on your codebase?

Full performance audit is ${price} if you want the deep dive.

- James
https://paypal.me/jamlen/{price}USD""",

    "code_quality": """Hey {user},

I noticed your code quality work on "{title_short}".

Refactoring and tech debt cleanup is hard to prioritize. SAGE helps by:

- Identifying the **highest-impact** code smells
- Mapping dependency tangles
- Finding duplicate/dead code
- Generating refactoring roadmaps

Happy to do a **free initial scan** of your repo.

Full repository audit is ${price} for a comprehensive report.

Interested?

Best,
James
https://paypal.me/jamlen/{price}USD""",

    "debugging": """Hi {user},

Saw your bug: "{title_short}"

Intermittent bugs are the worst. SAGE can help track it down:

- Pattern analysis across your codebase
- Race condition detection
- Error path tracing
- Similar bug matching from our database

Want me to take a quick look? **Free initial analysis.**

Deep crash investigation is ${price} if needed.

- James
https://paypal.me/jamlen/{price}USD"""
}


def get_high_value_leads(limit: int = 10) -> list:
    """Get highest value leads"""
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    
    c.execute("""
        SELECT identifier, data, score 
        FROM leads 
        WHERE status = 'new' 
          AND score >= 0.8
        ORDER BY score DESC 
        LIMIT ?
    """, (limit,))
    
    leads = []
    for row in c.fetchall():
        data = json.loads(row[1])
        data["score"] = row[2]
        data["identifier"] = row[0]
        leads.append(data)
    
    conn.close()
    return leads


def generate_high_value_outreach(lead: dict) -> dict:
    """Generate properly priced outreach for high-value lead"""
    category = lead.get("category", "code_quality")
    pricing = CATEGORY_PRICING.get(category, CATEGORY_PRICING["code_quality"])
    template = TEMPLATES.get(category, TEMPLATES["code_quality"])
    
    title = lead.get("title", "your issue")
    title_short = title[:50] + "..." if len(title) > 50 else title
    
    message = template.format(
        user=lead.get("user", "there"),
        title_short=title_short,
        price=pricing["price"]
    )
    
    return {
        "message": message,
        "product": pricing["product"],
        "price": pricing["price"],
        "category": category,
        "url": lead.get("url", ""),
        "user": lead.get("user", "")
    }


def send_outreach(lead: dict, outreach: dict) -> bool:
    """Post outreach to GitHub"""
    token_path = Path("/Eden/SECRETS/github_token.txt")
    if not token_path.exists():
        print(f"  [SKIP] No GitHub token")
        return False
    
    token = token_path.read_text().strip()
    url = lead.get("url", "")
    
    # Parse: https://github.com/owner/repo/issues/123
    try:
        parts = url.replace("https://github.com/", "").split("/")
        owner, repo, _, issue_num = parts[0], parts[1], parts[2], parts[3]
    except:
        print(f"  [ERROR] Cannot parse URL: {url}")
        return False
    
    api_url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_num}/comments"
    
    response = requests.post(
        api_url,
        headers={
            "Authorization": f"token {token}",
            "Accept": "application/vnd.github.v3+json"
        },
        json={"body": outreach["message"]},
        timeout=30
    )
    
    if response.status_code == 201:
        print(f"  ✅ SENT to {lead.get('user')} - ${outreach['price']}")
        # Mark lead as contacted
        conn = sqlite3.connect(DB_PATH)
        c = conn.cursor()
        c.execute("UPDATE leads SET status = 'contacted' WHERE identifier = ?", (lead["identifier"],))
        conn.commit()
        conn.close()
        return True
    else:
        print(f"  ❌ FAILED: {response.status_code}")
        return False


def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--preview', '-p', type=int, default=5, help='Preview N outreach messages')
    parser.add_argument('--send', '-s', type=int, help='Send N outreach messages')
    
    args = parser.parse_args()
    
    leads = get_high_value_leads(args.preview if not args.send else args.send)
    
    print("\n" + "="*60)
    print("  💎 HIGH-VALUE OUTREACH")
    print("="*60)
    
    for lead in leads:
        outreach = generate_high_value_outreach(lead)
        
        print(f"\n[{lead['score']:.2f}] {outreach['category'].upper()} - ${outreach['price']}")
        print(f"To: {lead.get('user')} @ {lead.get('url', '')[:50]}...")
        
        if args.send:
            send_outreach(lead, outreach)
        else:
            print(f"\n{outreach['message'][:300]}...")
        
        print("\n" + "─"*60)
    
    if not args.send:
        print(f"\n💡 To send these, run: --send {len(leads)}")


if __name__ == "__main__":
    main()
