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

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

import re
import random
from playwright.sync_api import Browser, Page
import asyncio


class Product_Scraper:
    domain: str
    page: Page

    def __init__(self, domain):
        print("Setting up browser automation")
        self.domain = domain
    
    @staticmethod
    def parse_cost(cost_text):
        if not cost_text:
            return None
        cost_clean = re.sub(r'[^\d,]', '', cost_text)
        try:
            return float(cost_clean) / 100
        except ValueError:
            return None
    
    async def scrape_cost_and_active_playwright(self, browser: Browser, url, page_load_element_selector, cost_selector, active_selector, invalid_active_statuses):
        # print(f"  Loading page...")
        self.page = await browser.new_page()
        await self.page.goto(url = url)
        await asyncio.sleep(random.uniform(20, 25))
        cost = None
        active = None
        try:
            element = self.page.locator(selector = page_load_element_selector)
            page_title = await self.page.title()
            # print(f"  Page title: {page_title}")
            
            element = self.page.locator(selector = cost_selector)
            text = await element.text_content()
            # print(f"    Text: '{text}'")
            cost = text
            
            active = None
            if active_selector is None:
                active = (cost is not None)
            else:
                # try:
                elements = await self.page.query_selector_all(selector = active_selector)
                # print(f'# active elements: {len(elements)}')
                if len(elements) == 0:
                    active = True
                else:
                    text = await elements[0].text_content()
                    text = text.strip()
                    # print(f"    Text: '{text}'")
                    active = (invalid_active_statuses is None or text not in invalid_active_statuses)
                # except Exception as e:
                    # print(f"  Selector failed: {e}")
                    # raise ValueError(f"Active selector failed: {e}")
            
            if cost is None or active is None:
                # print(f"  ✗ No cost found")
                # await ainput("Press Enter to continue to next URL...")
                raise Exception(f"Cost not found: {e}")
            # print(f"Cost: {cost}, Active: {active}")
            
        except Exception as e:
            # print(f"  Error: {e}")
            # await ainput("Press Enter to continue to next URL...")
            print(f"\n\nError getting costs: {e}\npage: {page_title}\ncost: {cost}\nactive: {active | text}")
            raise e
            return None, None
        finally:
            await self.page.close()
        return cost, active
