"""
Google Search Console Authentication Handler
Handles OAuth 2.0 authentication for Google Search Console API
"""

import os
import json
import pickle
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# Scopes required for Search Console API
SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly']

class GSCAuthenticator:
    def __init__(self, credentials_file='credentials.json', token_file='token.pickle'):
        """
        Initialize GSC authenticator
        
        Args:
            credentials_file: Path to OAuth 2.0 client credentials JSON
            token_file: Path to store authentication token
        """
        self.credentials_file = credentials_file
        self.token_file = token_file
        self.creds = None
        self.service = None
    
    def authenticate(self):
        """
        Authenticate with Google Search Console API
        
        Returns:
            Google Search Console service object
        """
        # Check if token already exists
        if os.path.exists(self.token_file):
            with open(self.token_file, 'rb') as token:
                self.creds = pickle.load(token)
        
        # If credentials are invalid or don't exist, get new ones
        if not self.creds or not self.creds.valid:
            if self.creds and self.creds.expired and self.creds.refresh_token:
                print("Refreshing expired credentials...")
                self.creds.refresh(Request())
            else:
                if not os.path.exists(self.credentials_file):
                    raise FileNotFoundError(
                        f"\n{'='*60}\n"
                        f"ERROR: {self.credentials_file} not found!\n\n"
                        f"To set up Google Search Console API:\n"
                        f"1. Go to https://console.cloud.google.com/\n"
                        f"2. Create a new project or select existing\n"
                        f"3. Enable 'Google Search Console API'\n"
                        f"4. Create OAuth 2.0 credentials (Desktop app)\n"
                        f"5. Download credentials and save as '{self.credentials_file}'\n"
                        f"{'='*60}\n"
                    )
                
                print("Starting OAuth flow...")
                flow = InstalledAppFlow.from_client_secrets_file(
                    self.credentials_file, SCOPES)
                self.creds = flow.run_local_server(port=0)
            
            # Save credentials for future use
            with open(self.token_file, 'wb') as token:
                pickle.dump(self.creds, token)
            print("Authentication successful!")
        
        # Build the service
        self.service = build('searchconsole', 'v1', credentials=self.creds)
        return self.service
    
    def list_properties(self):
        """
        List all Search Console properties the user has access to
        
        Returns:
            List of property URLs
        """
        if not self.service:
            self.authenticate()
        
        try:
            site_list = self.service.sites().list().execute()
            properties = [site['siteUrl'] for site in site_list.get('siteEntry', [])]
            return properties
        except Exception as e:
            print(f"Error listing properties: {e}")
            return []
    
    def verify_property_access(self, property_url):
        """
        Verify access to a specific property
        
        Args:
            property_url: URL of the property to verify
            
        Returns:
            Boolean indicating access
        """
        properties = self.list_properties()
        return property_url in properties


if __name__ == "__main__":
    # Test authentication
    print("Testing Google Search Console Authentication...")
    print("="*60)
    
    auth = GSCAuthenticator()
    
    try:
        service = auth.authenticate()
        print("\n✓ Authentication successful!")
        
        print("\nFetching your Search Console properties...")
        properties = auth.list_properties()
        
        if properties:
            print(f"\nFound {len(properties)} properties:")
            for i, prop in enumerate(properties, 1):
                print(f"  {i}. {prop}")
        else:
            print("\nNo properties found. Make sure you have access to Search Console.")
    
    except FileNotFoundError as e:
        print(e)
    except Exception as e:
        print(f"\n✗ Error: {e}")
