"""Bing search engine scraper."""

import logging
from typing import List
from urllib.parse import urlencode

from .base_scraper import BaseScraper
from ..models.schemas import SearchResult

logger = logging.getLogger(__name__)

class BingScraper(BaseScraper):
    """Bing search engine scraper."""
    
    def __init__(self):
        super().__init__("bing")
        self.base_url = "https://www.bing.com/search"
    
    def search(self, query: str, max_results: int = 10) -> List[SearchResult]:
        """Search Bing for results."""
        results = []
        
        try:
            params = {
                'q': query,
                'count': max_results,
                'first': 1,
                'FORM': 'PERE'
            }
            
            response = self._make_request(self.base_url, params)
            if not response:
                return results
            
            soup = self._parse_html(response.text)
            if not soup:
                return results
            
            # Find search result containers
            result_containers = soup.find_all('li', class_='b_algo')
            
            for i, container in enumerate(result_containers[:max_results]):
                try:
                    # Extract title and URL
                    title_elem = container.find('h2')
                    if not title_elem:
                        continue
                    
                    link_elem = title_elem.find('a')
                    if not link_elem:
                        continue
                    
                    title = link_elem.get_text(strip=True)
                    url = link_elem.get('href', '')
                    
                    # Extract description
                    desc_elem = container.find('div', class_='b_caption')
                    description = ""
                    if desc_elem:
                        desc_text = desc_elem.find('p')
                        if desc_text:
                            description = desc_text.get_text(strip=True)
                    
                    if title and url:
                        result = self._create_search_result(
                            title=title,
                            url=url,
                            description=description,
                            position=i + 1
                        )
                        results.append(result)
                        
                except Exception as e:
                    logger.error(f"Error parsing Bing result {i}: {e}")
                    continue
            
            logger.info(f"Bing: Found {len(results)} results for '{query}'")
            
        except Exception as e:
            logger.error(f"Bing search error: {e}")
        
        return results
