#!/usr/bin/env python3
"""
Brave Search Scanner — Fetch trending topics via Brave Search API.
Uses BRAVE_API_KEY from environment.
"""

import os
import requests
import json
from typing import List, Dict

# Brave Search keywords per niche (freshness: past day)
NICHE_KEYWORDS = {
    "USMC / Military": [
        "Marine Corps trending 2026",
        "veteran shirt design trending"
    ],
    "Military Family": [
        "military spouse community trending",
        "military family apparel"
    ],
    "Reformed Christian": [
        "Reformed theology trending",
        "Presbyterian social media viral"
    ],
    "Patriotic": [
        "patriotic apparel trending 2026",
        "American flag design viral"
    ],
    "Print on Demand": [
        "print on demand trending designs 2026",
        "Etsy trending niches March 2026"
    ],
    "AI Services / Small Business": [
        "AI automation small business trending",
        "ChatGPT tools SMB 2026"
    ]
}


def search_brave(query: str, api_key: str, count: int = 5) -> List[Dict]:
    """
    Search Brave Search API for recent results.
    Args:
        query: Search query string
        api_key: Brave API key
        count: Number of results to return
    Returns:
        List of result dicts with title, url, snippet
    """
    try:
        headers = {
            "Accept": "application/json",
            "X-Subscription-Token": api_key
        }
        params = {
            "q": query,
            "count": count,
            "freshness": "pd"  # Past day
        }
        
        url = "https://api.search.brave.com/res/v1/web/search"
        response = requests.get(url, headers=headers, params=params, timeout=10)
        response.raise_for_status()
        
        try:
            data = response.json()
        except json.JSONDecodeError:
            print(f"[WARN] Invalid JSON from Brave API for '{query}'")
            return []
        
        results = []
        if isinstance(data, dict) and "web" in data:
            for result in data.get("web", []):
                if isinstance(result, dict):
                    results.append({
                        "title": result.get("title", ""),
                        "url": result.get("url", ""),
                        "snippet": result.get("description", "")
                    })
        
        return results
    except Exception as e:
        # Suppress rate limit errors during test runs (expected)
        if "429" not in str(e):
            print(f"[WARN] Brave search failed for '{query}': {e}")
        return []


def get_brave_signals(niche: str, api_key: str) -> List[Dict]:
    """
    Get trending signals for a niche via Brave Search.
    Returns top signals with title, URL, niche tag.
    """
    if niche not in NICHE_KEYWORDS:
        return []
    
    keywords = NICHE_KEYWORDS[niche]
    all_signals = []
    
    for keyword in keywords:
        results = search_brave(keyword, api_key, count=3)
        for result in results:
            # Skip if title is too generic or short
            if len(result["title"]) > 10:
                all_signals.append({
                    "source": "brave",
                    "niche": niche,
                    "title": result["title"],
                    "snippet": result["snippet"],
                    "url": result["url"],
                    "engagement": 0  # Brave doesn't provide engagement metrics
                })
    
    return all_signals[:3]  # Top 3 per niche


if __name__ == "__main__":
    # Test run
    api_key = os.getenv("BRAVE_API_KEY")
    if not api_key:
        print("ERROR: BRAVE_API_KEY not found in environment")
        exit(1)
    
    for niche in NICHE_KEYWORDS.keys():
        signals = get_brave_signals(niche, api_key)
        print(f"\n{niche}:")
        for sig in signals:
            print(f"  • {sig['title']}")
