#!/usr/bin/env python3
"""
Apollo.io Bulk People Search
Searches for contacts by name + company
"""

import json
import requests
import time
from datetime import datetime

# REPLACE WITH YOUR APOLLO API KEY
APOLLO_API_KEY = "YOUR_API_KEY_HERE"

def search_person(first_name, last_name, company_name):
    """Search for a person on Apollo.io"""
    url = "https://api.apollo.io/v1/people/match"
    
    headers = {
        "Content-Type": "application/json",
        "X-Api-Key": APOLLO_API_KEY
    }
    
    data = {
        "first_name": first_name,
        "last_name": last_name,
        "organization_name": company_name
    }
    
    try:
        response = requests.post(url, headers=headers, json=data, timeout=10)
        
        if response.status_code == 200:
            result = response.json()
            if result.get('person'):
                person = result['person']
                return {
                    'email': person.get('email'),
                    'title': person.get('title'),
                    'linkedin_url': person.get('linkedin_url'),
                    'success': True
                }
        
        return {'success': False, 'error': f'HTTP {response.status_code}'}
    
    except Exception as e:
        return {'success': False, 'error': str(e)}


if __name__ == "__main__":
    # Load remaining problematic contacts
    with open('../remaining_problematic.json', 'r') as f:
        data = json.load(f)
    
    # Get all problematic contacts
    all_contacts = []
    for domain, contacts in data['by_domain'].items():
        all_contacts.extend(contacts)
    
    print(f"🔍 APOLLO BULK SEARCH")
    print("=" * 70)
    print(f"Total contacts to search: {len(all_contacts)}")
    print(f"API Key: {APOLLO_API_KEY[:10]}...")
    print("=" * 70)
    
    results = []
    found = 0
    
    for i, contact in enumerate(all_contacts[:60], 1):  # Free tier limit
        email = contact['email']
        company = contact['company']
        
        # Parse name from email
        email_parts = email.split('@')[0] if email else ''
        name_parts = email_parts.replace('.', ' ').replace('_', ' ').split()
        
        if len(name_parts) < 2:
            print(f"\n[{i}/60] Skipping (can't parse name): {email}")
            continue
        
        first_name = name_parts[0]
        last_name = ' '.join(name_parts[1:])
        
        print(f"\n[{i}/60] {first_name} {last_name} @ {company}")
        
        result = search_person(first_name, last_name, company)
        
        if result['success']:
            print(f"  ✅ Found: {result['email']} ({result['title']})")
            results.append({**contact, 'apollo_result': result})
            found += 1
        else:
            print(f"  ❌ Not found: {result.get('error', 'Unknown')}")
            results.append({**contact, 'apollo_result': result})
        
        time.sleep(1)  # Rate limiting
    
    # Save results
    output = {
        'timestamp': datetime.now().isoformat(),
        'total_searched': len(results),
        'found': found,
        'results': results
    }
    
    with open('apollo_results.json', 'w') as f:
        json.dump(output, f, indent=2)
    
    print("\n" + "=" * 70)
    print(f"✅ Complete - Found {found} contacts")
    print(f"💾 Saved to apollo_results.json")
