import os

from google.oauth2 import service_account
from googleapiclient.discovery import build
from loguru import logger

from app.config import BASE_DIR, GOOGLE_PLAY_CREDENTIALS_PATH, GOOGLE_PLAY_PACKAGE_NAME

_android_publisher = None


def get_android_publisher():
    global _android_publisher
    if _android_publisher is None:
        creds_path = os.path.join(BASE_DIR, GOOGLE_PLAY_CREDENTIALS_PATH)
        if not os.path.exists(creds_path):
            logger.warning(f"Google Play credentials not found at {creds_path}")
            return None
        credentials = service_account.Credentials.from_service_account_file(
            creds_path,
            scopes=["https://www.googleapis.com/auth/androidpublisher"],
        )
        _android_publisher = build("androidpublisher", "v3", credentials=credentials)
    return _android_publisher


def verify_subscription_v2(purchase_token: str):
    """Verify subscription using Subscriptions v2 API. Returns result dict or None."""
    publisher = get_android_publisher()
    if not publisher:
        return None
    return (
        publisher.purchases()
        .subscriptionsv2()
        .get(packageName=GOOGLE_PLAY_PACKAGE_NAME, token=purchase_token)
        .execute()
    )


def verify_subscription_v1(product_id: str, purchase_token: str):
    """Fallback: verify subscription using v1 API. Returns result dict or None."""
    publisher = get_android_publisher()
    if not publisher:
        return None
    return (
        publisher.purchases()
        .subscriptions()
        .get(
            packageName=GOOGLE_PLAY_PACKAGE_NAME,
            subscriptionId=product_id,
            token=purchase_token,
        )
        .execute()
    )
