"""
Project:    Shuffle & Skirmish Market Scraper
Author:     Edward Middleton-Smith
            Shuffle & Skirmish

Technology: Business Objects
Feature:    Card Market Product Scraper Class
"""

# Internal
from product_scraper import Product_Scraper
# External
import re
import random
from playwright.sync_api import Browser
import asyncio

class Card_Market_Product_Scraper(Product_Scraper):
    NAME_DOMAIN_CARD_MARKET: str = 'Card Market'

    def __init__(self):
        super().__init__(domain = self.NAME_DOMAIN_CARD_MARKET)

    @classmethod
    def parse_cost(cls, cost_text):
        """Convert '141,30 €' format to float in EUR"""
        if not cost_text:
            return None
        cost_clean = re.sub(r'[^\d,]', '', cost_text)
        cost_clean = cost_clean.replace(',', '.')
        try:
            return float(cost_clean)
        except ValueError:
            return None
        
    async def scrape_cost_and_active_playwright(self, browser, url, eur_to_gbp_rate):
        page_load_element_selector = "body > main.container > div.page-title-container"
        cost_selector = '#table > div:nth-child(1) > div.table-body > .row.article-row.g-0:nth-child(1) > div.col-offer > div.price-container > div > div:nth-child(1) > span:nth-child(1)'
        cost_text, active = await super().scrape_cost_and_active_playwright(
              browser = browser
            , url = url
            , page_load_element_selector = page_load_element_selector
            , cost_selector = cost_selector
            , active_selector = None
            , invalid_active_statuses = []
        )
        cost = self.parse_cost(cost_text = cost_text)
        if cost is not None:
            item_shipping_cost_in = 0
            if cost < 10:
                item_shipping_cost_in = 2
            elif cost < 100:
                item_shipping_cost_in = 8
            else:
                item_shipping_cost_in = 20
            cost = cost * eur_to_gbp_rate + item_shipping_cost_in
        active = (cost is not None)
        return cost, active

    async def scrape_prices_and_quantities_playwright(self, browser: Browser, url, eur_to_gbp_rate):
        offer_container_selector = '#table > div:nth-child(1) > div.table-body > .row.article-row.g-0:nth-child(1) > div.col-offer'
        price_selector = 'div.price-container > div > div:nth-child(1) > span:nth-child(1)'
        quantity_selector = 'div.amount-container > span:nth-child(1)'
        
        # print(f"  Loading page...")
        self.page = await browser.new_page()
        await self.page.goto(url = url)
        await asyncio.sleep(random.uniform(20, 25))
        
        price_quantity_pairs = []
        try:
            page_title = await self.page.title()
            # print(f"  Page title: {page_title}")
            
            offer_containers = await self.page.query_selector_all(offer_container_selector)
            # print(f"  Offer container selector: Found {len(offer_containers)} elements")
            for offer_container in offer_containers:
                price_element = await offer_container.query_selector(price_selector)
                price_text = await price_element.text_content()
                if '€' in price_text and re.search(r'\d', price_text):
                    # print(f"  ✓ Found price: {price_text}")
                    pass
                else:
                    price_text = None

                quantity_element = await offer_container.query_selector(quantity_selector)
                quantity_text = await quantity_element.text_content()
                
                if price_text is None or quantity_text is None:
                    continue
                price_quantity_pairs.append({
                      'price': self.parse_cost(cost_text = price_text) * eur_to_gbp_rate
                    , 'quantity': self.parse_cost(cost_text = quantity_text)
                })
        except Exception as e:
            # print(f"  Price selector failed: {e}")
            # await ainput("Press enter to continue to next URL...")
            print(f"\n\nError getting cardmarket prices: {e}\npage: {page_title}\nprices: {price_text}\nquantity: {quantity_text}")
            raise e # ValueError(f"Price selector failed: {e}")
            return []
        finally:
            await self.page.close()
        return price_quantity_pairs