"""Amazon site preset with validation and extraction."""
import time
import random
import re
import logging

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


class Amazon:
    RATE_LIMIT = 10
    _last_request = 0

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

    def _rate_limit(self):
        elapsed = time.time() - Amazon._last_request
        if elapsed < self.RATE_LIMIT:
            time.sleep(self.RATE_LIMIT - elapsed + random.uniform(0, 2))
        Amazon._last_request = time.time()

    def _validate_product_page(self, html: str) -> bool:
        """Check if we got a real product page."""
        if not html:
            return False
        
        indicators = [
            'id="productTitle"',
            'class="a-price-whole"',
            'data-asin=',
            'id="feature-bullets"',
            'Add to Cart',
            'buy-now-button'
        ]
        
        return any(indicator in html for indicator in indicators)

    def _extract_product_data(self, html: str, asin: str) -> dict:
        """Extract product data from Amazon page."""
        data = {"asin": asin}
        
        # Extract title
        title_match = re.search(r'id="productTitle"[^>]*>([^<]+)', html)
        if title_match:
            data['title'] = title_match.group(1).strip()
        
        # Extract price
        price_match = re.search(r'class="a-price-whole"[^>]*>([^<]+)', html)
        if price_match:
            data['price'] = price_match.group(1).strip()
        
        # Extract rating
        rating_match = re.search(r'data-hook="average-star-rating"[^>]*>.*?(\d\.\d)', html, re.DOTALL)
        if rating_match:
            data['rating'] = rating_match.group(1)
        
        # Extract review count
        reviews_match = re.search(r'data-hook="total-review-count"[^>]*>([^<]+)', html)
        if reviews_match:
            data['reviews'] = reviews_match.group(1).strip()
        
        return data

    def product(self, asin, country="US", extract=True):
        """Fetch Amazon product page by ASIN with extraction."""
        self._rate_limit()
        
        domain_map = {
            "US": "amazon.com",
            "UK": "amazon.co.uk", 
            "DE": "amazon.de",
            "FR": "amazon.fr",
            "JP": "amazon.co.jp",
            "CA": "amazon.ca",
            "ES": "amazon.es",
            "IT": "amazon.it"
        }
        
        domain = domain_map.get(country, "amazon.com")
        url = f"https://www.{domain}/dp/{asin}"
        
        from ..fingerprint import chrome_fingerprint
        resp = self.client.fetch(url, country=country, headers=chrome_fingerprint(country), retries=3)
        
        result = {
            "asin": asin,
            "url": url,
            "status": resp.status_code,
            "html": resp.text,
            "size_kb": len(resp.text) // 1024
        }
        
        if extract and resp.status_code == 200:
            if self._validate_product_page(resp.text):
                result["data"] = self._extract_product_data(resp.text, asin)
            else:
                result["data"] = {"asin": asin}
                logger.warning("Amazon product page validation failed")
        
        return result

    def search(self, query, country="US", extract=False):
        """Search Amazon with optional extraction."""
        self._rate_limit()
        import urllib.parse
        
        domain_map = {
            "US": "amazon.com",
            "UK": "amazon.co.uk",
            "DE": "amazon.de"
        }
        
        domain = domain_map.get(country, "amazon.com")
        encoded_query = urllib.parse.quote_plus(query)
        url = f"https://www.{domain}/s?k={encoded_query}"
        
        resp = self.client.fetch(url, country=country, retries=3)
        
        result = {
            "query": query,
            "url": url,
            "status": resp.status_code,
            "html": resp.text,
            "size_kb": len(resp.text) // 1024
        }
        
        if extract and resp.status_code == 200:
            # Basic search result extraction
            products = []
            product_matches = re.finditer(r'data-asin="([^"]+)"[^>]*>(.*?)</div>', resp.text, re.DOTALL)
            
            for match in product_matches:
                asin = match.group(1)
                product_html = match.group(2)
                
                title_match = re.search(r'<span[^>]*>([^<]+)</span>', product_html)
                title = title_match.group(1).strip() if title_match else ""
                
                if asin and title and len(asin) == 10:  # Valid ASIN
                    products.append({
                        'asin': asin,
                        'title': title
                    })
            
            result["products"] = products[:20]  # Limit results
        
        return result
