import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pathlib import Path
import logging

logger = logging.getLogger(__name__)

'''
class ApplicationTracker:
    def __init__(self, creds_path: str):
        self.scope = ["https://www.googleapis.com/auth/spreadsheets"]
        self.creds = ServiceAccountCredentials.from_json_keyfile_name(creds_path, self.scope)
    
    def track(self, application_data: dict):
        """Track application in Google Sheets with enhanced fields"""
        client = gspread.authorize(self.creds)
        sheet = client.open("Job Applications").sheet1
        
        sheet.append_row([
            application_data['company'],
            application_data['position'],
            application_data['date'],
            application_data['status'],
            application_data['score'],
            application_data['url'],
            application_data['resume_version'],
            application_data['notes']
        ])
'''
class ApplicationTracker:
    def __init__(self, creds_path: str):
        if not Path(creds_path).exists():
            raise FileNotFoundError(f"Credentials file not found at {creds_path}")
        
        try:
            self.scope = ["https://www.googleapis.com/auth/spreadsheets"]
            self.creds = ServiceAccountCredentials.from_json_keyfile_name(creds_path, self.scope)
            self.client = gspread.authorize(self.creds)
        except Exception as e:
            logger.error(f"Google Sheets auth failed: {e}")
            raise

    def track(self, application_data: dict, sheet_name="Job Applications"):
        try:
            sheet = self.client.open(sheet_name).sheet1
            sheet.append_row([
                application_data.get('company', ''),
                application_data.get('position', ''),
                application_data.get('date_applied', ''),
                application_data.get('status', 'Applied'),
                application_data.get('score', ''),
                application_data.get('url', '')
            ])
            return True
        except Exception as e:
            logger.error(f"Tracking failed: {e}")
            return False