# News search functionality for NovaChat
import requests
from bs4 import BeautifulSoup
import urllib.parse

def fetch_news(query, num_results=5):
    """Fetches news articles related to a query from Google News."""
    results = []
    try:
        # URL encode the query
        encoded_query = urllib.parse.quote_plus(query)
        # Construct Google News search URL
        url = f"https://news.google.com/search?q={encoded_query}&hl=en-US&gl=US&ceid=US:en"

        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }

        response = requests.get(url, headers=headers)
        response.raise_for_status() # Raise an exception for bad status codes

        soup = BeautifulSoup(response.text, 'html.parser')

        # Find news articles (selector might need adjustment if Google changes layout)
        articles = soup.find_all('article', limit=num_results)

        for article in articles:
            title_tag = article.find('h3')
            link_tag = article.find('a', href=True)
            source_tag = article.find('div', {'class': 'SVJrMe'}) # Class for source/time

            title = title_tag.text if title_tag else 'No Title'
            link = link_tag['href'] if link_tag else '#'
            # Construct absolute URL if relative
            if link.startswith('./'):
                link = "https://news.google.com" + link[1:]
            source = source_tag.text if source_tag else 'No Source'

            results.append({
                'title': title,
                'link': link,
                'source': source
            })

    except requests.exceptions.RequestException as e:
        print(f"Error fetching news: {e}")
        return [{'error': f"HTTP Error: {e}"}]
    except Exception as e:
        print(f"Error parsing news: {e}")
        return [{'error': f"Parsing Error: {e}"}]

    if not results:
        return [{'message': f"No news found for: {query}"}]

    return results

# Example usage (can be removed or moved)
if __name__ == '__main__':
    search_query = "latest technology trends"
    news_results = fetch_news(search_query)
    print(f"News results for '{search_query}':")
    for i, result in enumerate(news_results):
        if 'error' in result:
            print(f"Error: {result['error']}")
            break
        if 'message' in result:
            print(result['message'])
            break
        print(f"{i+1}. {result['title']}")
        print(f"   Source: {result['source']}")
        print(f"   Link: {result['link']}")
        print("---")