import pandas as pd
from openpyxl import load_workbook
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import re
import time
import random

ITEM_SHIPPING_COST_IN = 8

def parse_chaoscards_price(price_text):
    """Convert '141,30 €' format to float in EUR"""
    if not price_text:
        return None
    price_clean = re.sub(r'[^\d,]', '', price_text)
    try:
        return float(price_clean) / 100
    except ValueError:
        return None

def setup_driver():
    """Setup Chrome driver with visible window"""
    chrome_options = Options()
    # Remove headless mode to see the browser
    # chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36')
    chrome_options.add_argument('--window-size=1920,1080')
    
    try:
        driver = webdriver.Chrome(options=chrome_options)
        return driver
    except Exception as e:
        print(f"Error setting up Chrome driver: {e}")
        print("Make sure Chrome and chromedriver are installed")
        return None

def scrape_chaoscards_price_selenium(driver, url):
    try:
        print(f"  Loading page...")
        driver.get(url)
        
        time.sleep(random.uniform(5, 10))
        
        print(f"  Page title: {driver.title}")
        
        price_selector = '.price_inc > span:nth-child(2)'
        price = None
        try:
            element = driver.find_element(By.CSS_SELECTOR, price_selector)
            text = element.text
            print(f"    Text: '{text}'")
            price = parse_chaoscards_price(text)
        except Exception as e:
            print(f"  Selector failed: {e}")
        
        active_selector = '.product__right > form > ul.prod_det_fields.left.product-section.product-section--stock > li > div:nth-child(1) > div:nth-child(2)'
        active = None
        try:
            element = driver.find_element(By.CSS_SELECTOR, active_selector)
            text = element.text
            print(f"    Text: '{text}'")
            active = (text != "Out of stock")
        except Exception as e:
            print(f"  Selector failed: {e}")
        
        if price is None or active is None:
            print(f"  ✗ No price found")
            input("Press Enter to continue to next URL...")
        return price, active
        
    except Exception as e:
        print(f"  Error: {e}")
        return None, None

def main():
    workbook_name = 'TCG Sole Trader Copy.xlsx'
    sourcing_sheet_name = 'Sourcing'
    # product_sheet_name = 'Product'
    
    print("Loading workbook...")
    wb = load_workbook(workbook_name)
    
    if sourcing_sheet_name not in wb.sheetnames:
        print(f"Error: Sheet '{sourcing_sheet_name}' not found")
        return
    """
    if product_sheet_name not in wb.sheetnames:
        print(f"Error: Sheet '{product_sheet_name}' not found")
        return
    """
    sourcing_sheet = wb[sourcing_sheet_name]
    # product_sheet = wb[product_sheet_name]
    
    sourcing_table_found = False
    start_row = None
    for row in range(1, sourcing_sheet.max_row + 1):
        if sourcing_sheet.cell(row, 1).value == 'tbl_Sourcing' or 'Source Name' in str(sourcing_sheet.cell(row, 3).value):
            start_row = row + 1
            sourcing_table_found = True
            break
    
    if not sourcing_table_found or not start_row:
        for row in range(1, min(20, sourcing_sheet.max_row + 1)):
            if 'Source Name' in str(sourcing_sheet.cell(row, 3).value):
                start_row = row + 1
                sourcing_table_found = True
                break
    """
    start_row = None
    product_table_found = False
    for row in range(1, product_sheet.max_row + 1):
        if product_sheet.cell(row, 1).value == 'tbl_Product' or 'Product Id' in str(product_sheet.cell(row, 1).value):
            start_row = row + 1
            product_table_found = True
            break
    """
    if not sourcing_table_found:
        print("Error: Could not find table 'tbl_Sourcing'")
        return
    """
    if not product_table_found:
        print("Error: Could not find table 'tbl_Product'")
        return
    """

    # Find column indices
    header_row = start_row - 1
    source_name_col = None
    source_link_col = None
    source_unit_price_col = None
    source_is_available_col = None
    source_product_id_col = None
    """
    product_id_col = None
    product_is_booster_box_col = None
    product_is_precon_col = None
    """
    for col in range(1, sourcing_sheet.max_column + 1):
        header = str(sourcing_sheet.cell(header_row, col).value).strip()
        if 'Source Name' in header:
            source_name_col = col
        elif 'Source Link' in header:
            source_link_col = col
        elif 'Source Unit Cost' in header:
            source_unit_price_col = col
        elif 'Active' in header:
            source_is_available_col = col
        elif 'Product Id' in header:
            source_product_id_col = col
    """
    for col in range(1, product_sheet.max_column + 1):
        header = str(product_sheet.cell(header_row, col).value).strip()
        if 'Is Booster Box' in header:
            product_is_booster_box_col = col
        elif 'Is Precon' in header:
            product_is_precon_col = col
        elif 'Product Id' in header:
            product_id_col = col
    """
    print(f"Starting from row {start_row}")
    print(f"Sourcing Columns - Source Name: {source_name_col}, Source Link: {source_link_col}, Source Unit Cost: {source_unit_price_col}, Active: {source_is_available_col}, Product Id: {source_product_id_col}")
    # print(f"Product Columns - Id: {product_id_col}, Is Booster: {product_is_booster_box_col}, Is Precon: {product_is_precon_col}")

    if not all([source_name_col, source_link_col, source_unit_price_col, source_is_available_col, source_product_id_col]): # , product_id_col, product_is_booster_box_col, product_is_precon_col]):
        print("Error: Could not find required columns")
        return
    
    # Setup Selenium driver
    print("Setting up browser automation (browser will be visible)...")
    driver = setup_driver()
    if not driver:
        return
    
    try:
        processed_count = 0
        updated_count = 0
        
        for row in range(start_row, sourcing_sheet.max_row + 1):
            driver.quit()
            driver = setup_driver()
            if not driver:
                return
            
            source_name = sourcing_sheet.cell(row, source_name_col).value
            source_link = sourcing_sheet.cell(row, source_link_col).value
            source_product_id = sourcing_sheet.cell(row, source_product_id_col).value
            
            if not source_name and not source_link:
                break

            print(f"found source: {source_name} - product: {source_product_id} - link: {source_link}")
            
            if (
                    source_name == "Chaos Cards"
                and source_link
                and str(source_link).strip()
            ):
                sourcing_sheet.cell(row, source_unit_price_col).value = None
                sourcing_sheet.cell(row, source_is_available_col).value = "FALSE"

                processed_count += 1
                print(f"\n{'='*60}")
                print(f"Processing row {row}: {source_link}")
                print(f"{'='*60}")
                
                # Scrape price
                gbp_price, active = scrape_chaoscards_price_selenium(driver, source_link)
                
                if (gbp_price is not None and active is not None):
                    print(f"  Found price: {gbp_price}, active: {active}")
                    
                    if gbp_price:
                        sourcing_sheet.cell(row, source_unit_price_col).value = gbp_price + ITEM_SHIPPING_COST_IN
                        sourcing_sheet.cell(row, source_is_available_col).value = "TRUE" if active else "FALSE"
                        updated_count += 1
                    else:
                        print(f"  Error: Could not parse price")
                else:
                    print(f"  Error: Could not find price on page")
        # Save workbook
        print(f"\n{'='*60}")
        print(f"Saving workbook...")
        wb.save(workbook_name)
        
        print(f"\nComplete!")
        print(f"Processed: {processed_count} Chaos Cards entries")
        print(f"Updated: {updated_count} prices")
        
    finally:
        driver.quit()

if __name__ == "__main__":
    main()