from authlib.integrations.starlette_client import OAuth
from fastapi import HTTPException
import logging

# Initialize OAuth client (this could be re-used globally)
oauth = OAuth()

# Set up OAuth2 for Google, Apple, and Facebook (Example)
# Replace these with your actual credentials from their developer portals
oauth.register(
    name='google',
    client_id='YOUR_GOOGLE_CLIENT_ID',
    client_secret='YOUR_GOOGLE_CLIENT_SECRET',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    client_kwargs={'scope': 'openid profile email'},
)

oauth.register(
    name='apple',
    client_id='YOUR_APPLE_CLIENT_ID',
    client_secret='YOUR_APPLE_CLIENT_SECRET',
    authorize_url='https://appleid.apple.com/auth/authorize',
    access_token_url='https://appleid.apple.com/auth/token',
    client_kwargs={'scope': 'email'},
)

oauth.register(
    name='facebook',
    client_id='YOUR_FACEBOOK_CLIENT_ID',
    client_secret='YOUR_FACEBOOK_CLIENT_SECRET',
    authorize_url='https://www.facebook.com/v10.0/dialog/oauth',
    access_token_url='https://graph.facebook.com/v10.0/oauth/access_token',
    client_kwargs={'scope': 'email'},
)

# Define the social login logic
async def do_social_login(social_token: str, login_type: int, guest_id: str):
    """
    Handles social login for Google, Apple, and Facebook using their respective tokens.
    """
    user_info = None
    try:
        if login_type == 1:  # Google login
            user_info = await oauth.google.parse_id_token(social_token)
            return {"email": user_info.get('email'), "auth_key": "google_auth_key", "social_id": user_info.get('sub')}
        
        elif login_type == 2:  # Apple login
            user_info = await oauth.apple.parse_id_token(social_token)
            return {"email": user_info.get('email'), "auth_key": "apple_auth_key", "social_id": user_info.get('sub')}
        
        elif login_type == 3:  # Facebook login
            user_info = await oauth.facebook.get('me', params={'fields': 'id,email'})
            return {"email": user_info.get('email'), "auth_key": "facebook_auth_key", "social_id": user_info.get('id')}
        
    except Exception as e:
        logging.error(f"Social login failed: {e}")
        raise HTTPException(status_code=400, detail=f"Social login failed: {str(e)}")

    return None
