import os
from dataclasses import dataclass

from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build

from arkalos.core.config import config
from arkalos.data.extractors.data_extractor import DataExtractor

@dataclass
class GoogleExtractorConfig:
    SCOPES: list
    SERVICE_ACCOUNT_KEY_PATH: str

class GoogleExtractor(DataExtractor):

    __credentials = None

    @property
    def NAME(self) -> str:
        return 'Google'
    
    @property
    def TYPE(self) -> int:
        return self.TYPE_HTTP_REQUEST
    
    @property 
    def CONFIG(self): 
        return GoogleExtractorConfig(
            SCOPES = [
                'https://www.googleapis.com/auth/spreadsheets.readonly',
                'https://www.googleapis.com/auth/documents.readonly'
            ],
            SERVICE_ACCOUNT_KEY_PATH = config('data_sources.google.service_account_key_path')
        )
    
    @property 
    def TABLES(self): 
        return config('data_sources.google.spreadsheets')



    def __init__(self):
        self.__credentials = Credentials.from_service_account_file(
            self.CONFIG.SERVICE_ACCOUNT_KEY_PATH, 
            scopes=self.CONFIG.SCOPES
        )

    def __fetchSpreadsheet(self, spreadsheet_id):
        service = build('sheets', 'v4', credentials=self.__credentials)
        spreadsheet = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
    
        # Store results
        all_sheet_data = {}
        
        # Iterate through all sheets
        for sheet in spreadsheet.get('sheets', []):
            sheet_name = sheet['properties']['title']
            
            try:
                # Get the full range of the sheet
                sheet_metadata = service.spreadsheets().get(
                    spreadsheetId=spreadsheet_id, 
                    ranges=[sheet_name], 
                    includeGridData=False
                ).execute()
                
                # Get the last row and column
                grid_properties = sheet_metadata['sheets'][0]['properties']['gridProperties']
                last_row = grid_properties.get('rowCount', 1000)
                last_column = grid_properties.get('columnCount', 26)
                
                # Convert column count to A1 notation column letter
                last_column_letter = chr(64 + last_column)
                
                # Fetch all data
                range_name = f'{sheet_name}!A1:{last_column_letter}{last_row}'
                result = service.spreadsheets().values().get(
                    spreadsheetId=spreadsheet_id,
                    range=range_name
                ).execute()
                
                # Store the data
                all_sheet_data[sheet_name] = result.get('values', [])
                
            except Exception as e:
                print(f"Error retrieving data for sheet {sheet_name}: {e}")
        
        return all_sheet_data

    def fetchAllData(self, table_name):
        spreadsheet_id = self.getTableIdByName(table_name)
        return self.__fetchSpreadsheet(spreadsheet_id)

    def fetchSchema(self):
        pass

    def fetchUpdatedData(self, table_name, last_sync_date):
        pass

    def fetchAllIDs(self, table_name, column_name=None):
        pass

    def transformRow(self, data):
        pass

    # def get_doc_content(self, document_id):
    #     """
    #     Fetch content from Google Docs.
        
    #     Args:
    #         document_id (str): The ID of the document
            
    #     Returns:
    #         dict: The document content
    #     """
    #     try:
    #         service = build('docs', 'v1', credentials=self.credentials)
    #         document = service.documents().get(documentId=document_id).execute()
    #         return document
    #     except Exception as e:
    #         print(f"Error fetching document content: {str(e)}")
    #         return None

    # def extract_text_from_doc(self, document):
    #     """
    #     Extract plain text from a Google Doc structure.
        
    #     Args:
    #         document (dict): The document structure returned by the API
            
    #     Returns:
    #         str: Plain text content of the document
    #     """
    #     if not document or 'body' not in document:
    #         return ""
        
    #     text = []
    #     elements = document['body']['content']
        
    #     for element in elements:
    #         if 'paragraph' in element:
    #             for para_element in element['paragraph']['elements']:
    #                 if 'textRun' in para_element:
    #                     text.append(para_element['textRun']['content'])
        
    #     return ''.join(text)

# def main():
#     # Example usage
#     client = GoogleAPIClient()
#     client.authenticate()
    
#     # Example spreadsheet fetch
#     SPREADSHEET_ID = 'your_spreadsheet_id'
#     RANGE_NAME = 'Sheet1!A1:D10'
#     sheets_data = client.get_sheets_data(SPREADSHEET_ID, RANGE_NAME)
    
#     if sheets_data:
#         print("Spreadsheet data:")
#         for row in sheets_data:
#             print(row)
    
#     # Example document fetch
#     DOC_ID = 'your_document_id'
#     doc_content = client.get_doc_content(DOC_ID)
    
#     if doc_content:
#         plain_text = client.extract_text_from_doc(doc_content)
#         print("\nDocument content:")
#         print(plain_text)

# if __name__ == '__main__':
#     main()