"""Brave Search API integration.

Ported from gardener-fork/lib/brave_enrich.py with caching and county lookup.
"""

import json
import os
import re
import time
from pathlib import Path
from typing import List, Dict, Optional

import requests


BRAVE_API_BASE = "https://api.search.brave.com/res/v1/web/search"
DEFAULT_CACHE_PATH = "./data/city-county-cache.json"

CT_COUNTIES = [
    "Fairfield County", "Hartford County", "New Haven County",
    "New London County", "Litchfield County", "Middlesex County",
    "Tolland County", "Windham County",
]


def _get_api_key() -> str:
    """Get Brave API key from environment or config."""
    return os.environ.get("BRAVE_API_KEY", "")


def _get_cache_path() -> Path:
    """Get county cache file path."""
    path = os.environ.get("ABSEL_COUNTY_CACHE_PATH", DEFAULT_CACHE_PATH)
    return Path(path)


def _load_county_cache() -> Dict[str, str]:
    """Load county cache from disk."""
    cache_path = _get_cache_path()
    
    if not cache_path.exists():
        return {}
    
    try:
        with open(cache_path, 'r') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        return {}


def _save_county_cache(cache: Dict[str, str]) -> None:
    """Save county cache to disk."""
    cache_path = _get_cache_path()
    cache_path.parent.mkdir(parents=True, exist_ok=True)
    
    try:
        with open(cache_path, 'w') as f:
            json.dump(cache, f, indent=2)
    except IOError:
        pass


def brave_search(query: str, max_results: int = 5) -> List[Dict]:
    """Query Brave Search API. Returns list of result dicts with title/url/description.
    
    Args:
        query: Search query string
        max_results: Maximum number of results to return (default: 5)
    
    Returns:
        List of dicts with keys: title, url, description
    """
    api_key = _get_api_key()
    if not api_key:
        return []
    
    try:
        response = requests.get(
            BRAVE_API_BASE,
            headers={
                "Accept": "application/json",
                "X-Subscription-Token": api_key,
            },
            params={"q": query, "count": max_results},
            timeout=15,
        )
        response.raise_for_status()
        
        data = response.json()
        web = data.get("web", {}).get("results", [])
        
        results = []
        for r in web:
            results.append({
                "title": r.get("title", ""),
                "url": r.get("url", ""),
                "description": r.get("description", ""),
            })
        
        return results
        
    except (requests.RequestException, json.JSONDecodeError):
        return []


def _extract_phone(text: str) -> str:
    """Extract phone number from text."""
    patterns = [
        r'\b\d{3}[-.)]\s*\d{3}[-.]\s*\d{4}\b',
        r'\b\(\d{3}\)\s*\d{3}[-.]\s*\d{4}\b',
        r'\b\d{3}\.\d{3}\.\d{4}\b',
    ]
    
    for pat in patterns:
        match = re.search(pat, text)
        if match:
            return match.group(0)
    
    return ""


def _extract_website_url(results: List[Dict]) -> str:
    """Extract website URL from search results, skipping aggregators."""
    skip_domains = [
        "facebook.com", "linkedin.com", "yelp.com", "bbb.org",
        "yellowpages.com", "manta.com", "mapquest.com", "superpages.com",
        "google.com/maps", "birdeye.com",
    ]
    
    for r in results:
        url = r.get("url", "")
        if url and not any(skip in url.lower() for skip in skip_domains):
            return url
    
    return ""


def _lookup_county(city: str) -> str:
    """Lookup county for a CT city using cache."""
    cache = _load_county_cache()
    city_lower = (city or "").lower().strip()
    
    if not city_lower:
        return ""
    
    if city_lower in cache:
        return cache[city_lower]
    
    query = f"{city} CT county"
    results = brave_search(query, max_results=3)
    
    for r in results:
        text = (r.get("title", "") + " " + r.get("description", "")).lower()
        for county in CT_COUNTIES:
            if county.lower() in text:
                cache[city_lower] = county
                _save_county_cache(cache)
                return county
    
    cache[city_lower] = ""
    _save_county_cache(cache)
    return ""


def brave_enrich_lead(lead: dict) -> dict:
    """Search Brave for the lead's business. Returns enrichment dict.
    
    Args:
        lead: Lead dict with name and city fields
    
    Returns:
        Dict with keys:
        - brave_summary: first useful description text (or empty)
        - brave_phone: phone extracted from results (or empty)
        - brave_descriptions: list of description snippets
        - brave_website: website URL if discovered (or empty)
        - county: county lookup result (cached) or empty
    """
    api_key = _get_api_key()
    if not api_key:
        return {}
    
    name = (lead.get("name") or "").strip()
    city = (lead.get("city") or "CT").strip()
    
    if not name:
        return {}
    
    biz_query = f"{name} {city} CT"
    biz_results = brave_search(biz_query, max_results=5)
    
    time.sleep(0.2)
    
    county = _lookup_county(city)
    
    phone = ""
    descriptions = []
    
    for r in biz_results:
        desc = r.get("description", "")
        if desc:
            descriptions.append(desc[:300])
        if not phone:
            phone = _extract_phone(r.get("title", "") + " " + desc)
    
    website = _extract_website_url(biz_results)
    
    summary = descriptions[0] if descriptions else ""
    
    return {
        "brave_phone": phone,
        "brave_descriptions": descriptions,
        "brave_summary": summary,
        "brave_website": website,
        "county": county,
        "brave_results_count": len(biz_results),
    }