from django.conf import settings
from googleapiclient.discovery import build
from google.oauth2 import service_account
from core.logger import logger


class GooglePlayVerifier:
    """Google Play in-app purchase/subscription verification via AndroidPublisher API.
    Requires a service account JSON and the Android Publisher API enabled in google console.
    Environment variables expected (set in settings or env):
    - ANDROID_PACKAGE (e.g., 'com.app.projectname')
    - GOOGLE_APPLICATION_CREDENTIALS (path to service account JSON) in settings.py
    """

    def __init__(self):
        SCOPES = ['https://www.googleapis.com/auth/androidpublisher']
        credentials = service_account.Credentials.from_service_account_file(
            filename=settings.GOOGLE_PLAY_SERVICE_ACCOUNT,
            scopes=SCOPES)
        self.service = build("androidpublisher", "v3", credentials=credentials)

    def verify_subscription(self, product_id, purchase_token):
        try:
            subscription = (
                self.service.purchases()
                .subscriptionsv2()
                .get(packageName=settings.PACKAGE_NAME, token=purchase_token)
                .execute()
            )
            logger.info(f"Google verify_subscription succeeded.")
            return {"isSuccessful": True, "payload": subscription}
        except Exception as e:
            logger.info(f"Error in Google verify_subscription: {e}")
            return {"isSuccessful": False, "errorMessage": str(e)}

    def verify_inapp(self, product_id, purchase_token):
        try:
            inapp = (
                self.service.purchases()
                .products()
                .get(packageName=settings.PACKAGE_NAME, productId=product_id, token=purchase_token)
                .execute()
            )
            logger.info("Google inapp payload: %s", inapp)
            return {"isSuccessful": True, "payload": inapp}
        except Exception as e:
            print(e, '>>>>>>>>>>>>>>>>>>>>>>ERROR')
            # logger.exception("Google verify_inapp error")
            return {"isSuccessful": False, "errorMessage": str(e)}
