# Constants SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] # Global analytics service analytics_service = None # Load environment variables from .env file load_dotenv() def init_ga4_client(): """Initialize Google Analytics 4 client using service account.""" global analytics_service # Get service account file path from environment variable service_account_file = os.getenv('GOOGLE_APPLICATION_CREDENTIALS') if not service_account_file: raise ValueError("GOOGLE_APPLICATION_CREDENTIALS environment variable is required") if not os.path.exists(service_account_file): raise FileNotFoundError(f"Service account file not found: {service_account_file}") # Get property ID from environment variable property_id = os.getenv('GA4_PROPERTY_ID') if not property_id: raise ValueError("GA4_PROPERTY_ID environment variable is required") # Authenticate using service account credentials credentials = service_account.Credentials.from_service_account_file( service_account_file, scopes=SCOPES) # Build the Google Analytics Data API client (for GA4) analytics_service = build('analyticsdata', 'v1beta', credentials=credentials) __ __