"""Google News RSS fallback for blocked news/business sites."""
import re
import logging
import xml.etree.ElementTree as ET

logger = logging.getLogger("iploop.sites.google_news")

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"


class GoogleNews:
    """Fetch news via Google News RSS — works as fallback for Bloomberg, Reuters, etc."""

    def __init__(self, client):
        self.client = client

    def extract(self, url=None, query=None, site_filter=None):
        """
        Fetch Google News RSS for a query.
        
        Args:
            url: Original URL (used to guess query if query not given)
            query: Direct search query
            site_filter: Limit to a domain, e.g. "bloomberg.com"
        """
        if not query and url:
            # Guess query from URL
            query = re.sub(r'https?://(www\.)?', '', url).split('/')[0]
        if not query:
            return {"success": False, "data": {}, "source": "google-news-rss", "error": "No query"}

        search = query
        if site_filter:
            search = f"site:{site_filter} {query}"

        rss_url = f"https://news.google.com/rss/search?q={requests.utils.quote(search)}&hl=en-US&gl=US&ceid=US:en"
        
        try:
            resp = self.client.fetch(rss_url, timeout=10, headers={"User-Agent": UA})
            if resp.status_code != 200:
                return {"success": False, "data": {}, "source": "google-news-rss", "error": f"HTTP {resp.status_code}"}

            root = ET.fromstring(resp.text)
            items = []
            for item in root.findall('.//item')[:15]:
                title_el = item.find('title')
                link_el = item.find('link')
                pub_el = item.find('pubDate')
                source_el = item.find('source')
                items.append({
                    "title": title_el.text if title_el is not None else "",
                    "link": link_el.text if link_el is not None else "",
                    "published": pub_el.text if pub_el is not None else "",
                    "source": source_el.text if source_el is not None else "",
                })

            if items:
                return {
                    "success": True,
                    "data": {"query": query, "count": len(items), "articles": items},
                    "source": "google-news-rss",
                    "error": None
                }
            return {"success": False, "data": {}, "source": "google-news-rss", "error": "No results"}
        except Exception as e:
            return {"success": False, "data": {}, "source": "google-news-rss", "error": str(e)}

    def search(self, query, site_filter=None):
        """Direct search convenience method."""
        return self.extract(query=query, site_filter=site_filter)
