#!/usr/bin/env python3
"""
EDEN WHALE ENRICHER (Agentic Research)
Target: Sacred Whales (Top 1%)
Mission: Find the HUMAN behind the repository.
"""
import sqlite3
import requests
import time
import json
from datetime import datetime

# DB Paths
SALES_DB = "/Eden/DATA/sales.db"

def get_sacred_targets():
    """Fetch un-enriched whales"""
    conn = sqlite3.connect(SALES_DB)
    # Get top 10 un-enriched whales
    targets = conn.execute("SELECT target, whale_tier FROM sacred_targets WHERE enriched=0 ORDER BY score DESC LIMIT 5").fetchall()
    conn.close()
    return targets

def enrich_target(target_name):
    """
    Agentic Loop to find the 'Alpha' of the repo.
    Logic: The Owner or Top Contributor is the decision maker.
    """
    print(f"🕵️‍♀️ Investigating Whale: {target_name}...")
    
    # 1. GitHub API Recon (No auth needed for public, but rate limited - fine for stealth)
    url = f"https://api.github.com/users/{target_name}"
    try:
        r = requests.get(url)
        if r.status_code != 200:
            # Maybe it's an Org?
            url = f"https://api.github.com/orgs/{target_name}"
            r = requests.get(url)
            
        data = r.json()
        
        # 2. Extract Intelligence
        dossier = {
            "name": data.get("name", target_name),
            "blog": data.get("blog", ""),
            "email": data.get("email", "Hidden"),
            "bio": data.get("bio", ""),
            "location": data.get("location", ""),
            "twitter": data.get("twitter_username", ""),
            "followers": data.get("followers", 0),
            "created_at": data.get("created_at", "")
        }
        
        # 3. If Email is hidden, look for 'Alpha' member (Top public member)
        if not dossier['email'] and data.get('type') == 'Organization':
            print(f"   > Org detected. Hunting for the Alpha member...")
            members_url = f"https://api.github.com/orgs/{target_name}/public_members"
            m_r = requests.get(members_url)
            if m_r.status_code == 200:
                members = m_r.json()
                if members:
                    # Pick first member (usually founder/admin)
                    alpha = members[0]
                    print(f"   > Alpha Found: {alpha['login']}")
                    # Recursive dip
                    a_r = requests.get(alpha['url'])
                    a_data = a_r.json()
                    dossier['alpha_contact'] = {
                        "handle": alpha['login'],
                        "name": a_data.get("name"),
                        "bio": a_data.get("bio"),
                        "email": a_data.get("email") # The Gold
                    }
        
        return dossier
        
    except Exception as e:
        print(f"❌ Research Failed: {e}")
        return None

def save_intel(target, data):
    """Save the dossier to the DB"""
    conn = sqlite3.connect(SALES_DB)
    
    # Store raw dossier as JSON string
    intel_json = json.dumps(data)
    
    # Update sacred_targets
    conn.execute("UPDATE sacred_targets SET enriched=1, profiling_data=? WHERE target=?", 
                 (intel_json, target))
    
    # If we found an email, add to High Priority Leads
    email = data.get('email') or data.get('alpha_contact', {}).get('email')
    if email:
        print(f"🎯 GOLD FOUND: {email}")
        conn.execute("UPDATE sacred_targets SET email=? WHERE target=?",
                    (email, target))
    
    conn.commit()
    conn.close()
    print(f"✅ Dossier filed for {target}")

if __name__ == "__main__":
    print("🦁 EDEN ENRICHMENT PROTOCOL ENGAGED")
    whales = get_sacred_targets()
    
    if not whales:
        print("😴 No un-enriched whales found.")
    
    for target_name, tier in whales:
        intel = enrich_target(target_name)
        if intel:
            save_intel(target_name, intel)
            time.sleep(2) # Stealth delay
