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

Technology: Business Objects
Feature:    TCG Sole Trader Workbook Container Class
"""

import pandas as pd
from openpyxl import load_workbook, Workbook
from openpyxl.worksheet.worksheet import Worksheet

class TCG_Sole_Trader_Workbook_Container:
    NAME_COLUMN_ACTIVE: str = 'Active'
    NAME_COLUMN_INDEX_ROW: str = 'Index Row'
    NAME_COLUMN_LINK: str = 'Link'
    NAME_COLUMN_PRODUCT_ID: str = 'Product Id'
    NAME_COLUMN_PRODUCT_IS_BOOSTER: str = 'Product Is Booster'
    NAME_COLUMN_PRODUCT_IS_BOOSTER_BOX: str = 'Product Is Booster Box'
    NAME_COLUMN_PRODUCT_IS_PRECON: str = 'Product Is Precon'
    NAME_COLUMN_SOURCE_NAME: str = 'Source Name'
    NAME_COLUMN_UNIT_COST: str = 'Cost'
    NAME_COLUMN_UNIT_PRICE: str = 'Price'
    PRODUCT_WORKSHEET_NAME = 'Product'
    SOURCING_WORKSHEET_NAME = 'Sourcing'
    WORKBOOK_NAME = 'TCG Sole Trader Copy.xlsx'

    index_column_active_sourcing: int
    index_column_is_booster_product: int
    index_column_is_booster_box_product: int
    index_column_is_precon_product: int
    index_column_link_sourcing: int
    index_column_name_sourcing: int
    index_column_product_id_product: int
    index_column_product_id_sourcing: int
    index_column_unit_cost_sourcing: int
    index_column_unit_price_sourcing: int
    index_row_header_product: int
    index_row_header_sourcing: int
    product_sheet: Worksheet
    sourcing_sheet: Worksheet
    workbook: Workbook

    def __init__(self):
        print("Loading workbook...")
        self.workbook = load_workbook(self.WORKBOOK_NAME)
        
        if self.SOURCING_WORKSHEET_NAME not in self.workbook.sheetnames:
            print(f"Error: Sheet '{self.SOURCING_WORKSHEET_NAME}' not found")
            return
        if self.PRODUCT_WORKSHEET_NAME not in self.workbook.sheetnames:
            print(f"Error: Sheet '{self.PRODUCT_WORKSHEET_NAME}' not found")
            return
        
        self.sourcing_sheet = self.workbook[self.SOURCING_WORKSHEET_NAME]
        self.product_sheet = self.workbook[self.PRODUCT_WORKSHEET_NAME]
        
        sourcing_table_found = False
        for row in range(1, self.sourcing_sheet.max_row + 1):
            if self.sourcing_sheet.cell(row, 1).value == 'tbl_Sourcing' or 'Source Name' in str(self.sourcing_sheet.cell(row, 3).value):
                self.index_row_header_sourcing = row
                sourcing_table_found = True
                break
        
        if not sourcing_table_found or not self.index_row_header_sourcing:
            for row in range(1, min(20, self.sourcing_sheet.max_row + 1)):
                if 'Source Name' in str(self.sourcing_sheet.cell(row, 3).value):
                    self.index_row_header_sourcing = row
                    sourcing_table_found = True
                    break
        
        if not sourcing_table_found:
            print("Error: Could not find table 'tbl_Sourcing'")
            return
        
        product_table_found = False
        for row in range(1, self.product_sheet.max_row + 1):
            if self.product_sheet.cell(row, 1).value == 'tbl_Product' or 'Product Id' in str(self.product_sheet.cell(row, 1).value):
                self.index_row_header_product = row
                product_table_found = True
                break
        
        if not product_table_found:
            print("Error: Could not find table 'tbl_Product'")
            return
        
        for index_column in range(1, self.sourcing_sheet.max_column + 1):
            header = str(self.sourcing_sheet.cell(self.index_row_header_sourcing, index_column).value).strip()
            if 'Source Name' == header:
                self.index_column_name_sourcing = index_column
            elif 'Source Link' == header:
                self.index_column_link_sourcing = index_column
            elif 'Source Unit Cost' == header:
                self.index_column_unit_cost_sourcing = index_column
            elif 'Sale Price' == header:
                self.index_column_unit_price_sourcing = index_column
            elif 'Active' == header:
                self.index_column_active_sourcing = index_column
            elif 'Product Id' == header:
                self.index_column_product_id_sourcing = index_column
        
        for index_column in range(1, self.product_sheet.max_column + 1):
            header = str(self.product_sheet.cell(self.index_row_header_product, index_column).value).strip()
            if 'Is Booster Box' == header:
                self.index_column_is_booster_box_product = index_column
            elif 'Is Booster' == header:
                self.index_column_is_booster_product = index_column
            elif 'Is Precon' == header:
                self.index_column_is_precon_product = index_column
            elif 'Product Id' == header:
                self.index_column_product_id_product = index_column
        
        print(f"Sourcing max row: {self.sourcing_sheet.max_row}")
        print(f"Sourcing header row: {self.index_row_header_sourcing}")
        print(f"Sourcing header 1: {self.sourcing_sheet.cell(self.index_row_header_sourcing, 1).value}")
        print(f"Sourcing Columns - Name: {self.index_column_name_sourcing}, Link: {self.index_column_link_sourcing}, Unit Cost: {self.index_column_unit_cost_sourcing}, Sale price: {self.index_column_unit_price_sourcing}, Active: {self.index_column_active_sourcing}, Product Id: {self.index_column_product_id_sourcing}")
        print(f"Product max row: {self.product_sheet.max_row}")
        print(f"Product header row: {self.index_row_header_product}")
        print(f"Sourcing header 1: {self.product_sheet.cell(self.index_row_header_product, 1).value}")
        print(f"Product Columns - Id: {self.index_column_product_id_product}, Is Booster: {self.index_column_is_booster_product}, Is Booster Box: {self.index_column_is_booster_box_product}, Is Precon: {self.index_column_is_precon_product}")

        if not all([
              self.index_column_name_sourcing
            , self.index_column_link_sourcing
            , self.index_column_unit_cost_sourcing
            , self.index_column_unit_price_sourcing
            , self.index_column_product_id_sourcing
            , self.index_column_active_sourcing
            , self.index_column_product_id_product
            , self.index_column_is_booster_product
            , self.index_column_is_booster_box_product
            , self.index_column_is_precon_product
        ]):
            print("Error: Could not find required columns")
            return

    @classmethod
    def create_product_source_df(cls):
        return pd.DataFrame(columns = [
              cls.NAME_COLUMN_INDEX_ROW
            , cls.NAME_COLUMN_PRODUCT_ID
            , cls.NAME_COLUMN_SOURCE_NAME
            , cls.NAME_COLUMN_LINK
            , cls.NAME_COLUMN_PRODUCT_IS_BOOSTER
            , cls.NAME_COLUMN_UNIT_COST
            , cls.NAME_COLUMN_UNIT_PRICE
            , cls.NAME_COLUMN_ACTIVE
        ])
    
    def get_sourcing_entries(self):
        product_sources = self.create_product_source_df()
        try:
            for index_row in range(self.index_row_header_sourcing + 1, self.sourcing_sheet.max_row + 1):
                source_name = self.sourcing_sheet.cell(index_row, self.index_column_name_sourcing).value
                source_link = self.sourcing_sheet.cell(index_row, self.index_column_link_sourcing).value
                source_product_id = self.sourcing_sheet.cell(index_row, self.index_column_product_id_sourcing).value
                if not source_name or not source_link:
                    continue
                # print(f"found source: {source_name} - product: {source_product_id} - link: {source_link}")
                product_is_booster = False
                for product_row in range(self.index_row_header_product + 1, self.product_sheet.max_row + 1):
                    product_id = self.product_sheet.cell(product_row, self.index_column_product_id_product).value
                    if product_id == source_product_id:
                        product_is_booster_text = str(self.product_sheet.cell(product_row, self.index_column_is_booster_product).value).upper()
                        product_is_booster = (product_is_booster_text == "TRUE")
                        break
                # print(f"product is booster: {product_is_booster}")

                product_sources.loc[len(product_sources)] = [
                    index_row
                    , source_product_id
                    , source_name
                    , source_link
                    , product_is_booster
                    , None # cost
                    , None # price
                    , None # active
                ]
        except Exception as e:
            print(f"Error: {e}")
        product_sources.sort_values(self.NAME_COLUMN_SOURCE_NAME)
        return product_sources
    
    def clear_row_sourcing_sheet(self, index_row):
        self.sourcing_sheet.cell(index_row, self.index_column_unit_cost_sourcing).value = None
        self.sourcing_sheet.cell(index_row, self.index_column_active_sourcing).value = "FALSE"
    
    def update_row_sourcing_sheet(self, index_row, unit_cost = None, unit_price = None, active = None):
        if unit_cost is not None:
            self.sourcing_sheet.cell(index_row, self.index_column_unit_cost_sourcing).value = unit_cost
        if unit_price is not None:
            self.sourcing_sheet.cell(index_row, self.index_column_unit_price_sourcing).value = unit_price
        if active is not None:
            self.sourcing_sheet.cell(index_row, self.index_column_active_sourcing).value = "TRUE" if active else "FALSE"
    
    def save_workbook(self):
        print(f"\n{'='*60}")
        print(f"Saving workbook...")
        self.workbook.save(self.WORKBOOK_NAME)
    