import requests
import json
import logging

logger = logging.getLogger(__name__)

# Keys provided in the user prompt
KEYS = {
    "NUMLOOKUP": "num_live_iViCHWVuE5tWiAsSBimesKfrD3w2VDgA748z9Btw",
    "ABSTRACT": "bdf209a5a133453cbf82f4a0f098773d",
    "VERIPHONE": "885174620DD34D3A80B4E57BA05036E3",
    "HUNTERIO": "374d3258ec737081b981b693ac6590661c87c60d",
    "OPENCELLID": "1f8f328afa8ba5",
    "OPENCAGE": "f8c073589bca4d09b09a50e7c600ee10",
    "SERPAPI": "eee2937a45ff20f37c91be7f73f8264ed2b4c07c7e58e6a4348ab84e249ee72b",
}

def phone_lookup(number):
    """Unified phone lookup from multiple sources"""
    results = {}
    
    # 1. NumLookup
    try:
        url = f"https://api.numlookupapi.com/v1/validate/{number}?apikey={KEYS['NUMLOOKUP']}"
        resp = requests.get(url, timeout=5)
        if resp.status_code == 200:
            results['numlookup'] = resp.json()
    except Exception as e:
        logger.error(f"NumLookup error: {e}")

    # 2. Veriphone
    try:
        url = f"https://veriphone.com/api/v1/verify?phone={number}&key={KEYS['VERIPHONE']}"
        resp = requests.get(url, timeout=5)
        if resp.status_code == 200:
            results['veriphone'] = resp.json()
    except Exception as e:
        logger.error(f"Veriphone error: {e}")

    return results

def email_lookup(email):
    """Unified email lookup"""
    results = {}
    
    # 1. Hunter.io
    try:
        url = f"https://api.hunter.io/v2/email-verifier?email={email}&api_key={KEYS['HUNTERIO']}"
        resp = requests.get(url, timeout=5)
        if resp.status_code == 200:
            results['hunter'] = resp.json().get('data', {})
    except Exception as e:
        logger.error(f"Hunter.io error: {e}")

    # 2. Abstract API
    try:
        url = f"https://emailvalidation.abstractapi.com/v1/?api_key={KEYS['ABSTRACT']}&email={email}"
        resp = requests.get(url, timeout=5)
        if resp.status_code == 200:
            results['abstract'] = resp.json()
    except Exception as e:
        logger.error(f"Abstract error: {e}")

    return results

def serp_search(query):
    """Google search via SerpAPI for public mentions"""
    try:
        url = "https://serpapi.com/search.json"
        params = {
            "q": query,
            "api_key": KEYS['SERPAPI'],
            "engine": "google"
        }
        resp = requests.get(url, params=params, timeout=10)
        if resp.status_code == 200:
            return resp.json().get('organic_results', [])
    except Exception as e:
        logger.error(f"SerpAPI error: {e}")
    return []
