from flask import session, redirect, url_for
from google_auth_oauthlib.flow import Flow
from google.oauth2 import id_token
import google.auth.transport.requests
from pip._vendor import cachecontrol
import requests
import uuid
from app import mysql
from app.config import Config
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
import os
from app.config import Config


class GoogleAuthService:
    CLIENT_SECRETS_FILE = "config/client_secrets.json"
    SCOPES = [
        'https://www.googleapis.com/auth/userinfo.email',
        'https://www.googleapis.com/auth/userinfo.profile',
        'openid'
    ]
    call_back_url = f"{Config.url}/auth/google/callback"
    @staticmethod
    def initiate_auth():
        try:
            flow = Flow.from_client_secrets_file(
                GoogleAuthService.CLIENT_SECRETS_FILE,
                scopes=GoogleAuthService.SCOPES,
                redirect_uri= GoogleAuthService.call_back_url
            )
            authorization_url, state = flow.authorization_url(
                access_type='offline',
                include_granted_scopes='true'
            )
            session['state'] = state
            return redirect(authorization_url)
        except Exception as e:
            print(f"Error in initiate_auth: {str(e)}")
            return redirect(url_for('auth.login'))

    @staticmethod
    def handle_callback(code):
        try:
            flow = Flow.from_client_secrets_file(
                GoogleAuthService.CLIENT_SECRETS_FILE,
                scopes=GoogleAuthService.SCOPES,
                redirect_uri= GoogleAuthService.call_back_url
            )
            flow.fetch_token(code=code)
            credentials = flow.credentials

            service = build('oauth2', 'v2', credentials=credentials)
            user_info = service.userinfo().get().execute()

            return {
                'id': user_info.get('id'),
                'email': user_info.get('email'),
                'name': user_info.get('name')
            }
        except Exception as e:
            print(f"Error in handle_callback: {str(e)}")
            return None