# app/services/android_receipt_validator.py

import os
import json
import traceback
from dotenv import load_dotenv
from fastapi import HTTPException
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

load_dotenv()

google_json_key_path = os.getenv("JSON_KEY_PATH_ANDROID_SUB", "")
android_pkg_name = os.getenv("ANDROID_PKG_NAME", "")


class AndroidReceiptValidator:
    def __init__(self):
        try:
            credentials = service_account.Credentials.from_service_account_file(
                google_json_key_path,
                scopes=["https://www.googleapis.com/auth/androidpublisher"],
            )
            self.android_publisher = build(
                "androidpublisher", "v3", credentials=credentials
            )
        except Exception as e:
            raise HTTPException(
                status_code=500, detail=f"Google Auth Init Failed: {str(e)}"
            )

    def validateProduct(self, product_id: str, purchase_token: str):
        """
        Validate Android subscription purchase
        """
        try:
            response = (
                self.android_publisher.purchases()
                .subscriptions()
                .get(
                    packageName=android_pkg_name,
                    subscriptionId=product_id,
                    token=purchase_token,
                )
                .execute()
            )
            return {"isValid": True, "response": response}

        except HttpError as e:
            # Google API errors often include JSON
            try:
                error_json = json.loads(e.content.decode("utf-8"))
            except Exception:
                error_json = {"error": {"message": str(e)}}

            return {"isValid": False, "response": error_json}

        except Exception as e:
            return {
                "isValid": False,
                "response": {"error": {"message": str(e), "trace": traceback.format_exc()}},
            }

    def validate_inapp(self, package_name: str, product_id: str, purchase_token: str):
        """
        Validate Android in-app purchase
        """
        try:
            response = (
                self.android_publisher.purchases()
                .products()
                .get(
                    packageName=package_name,
                    productId=product_id,
                    token=purchase_token,
                )
                .execute()
            )
            return {"isValid": True, "response": response}

        except HttpError as e:
            try:
                error_json = json.loads(e.content.decode("utf-8"))
            except Exception:
                error_json = {"error": {"message": str(e)}}

            return {"isValid": False, "response": error_json}

        except Exception as e:
            return {
                "isValid": False,
                "response": {"error": {"message": str(e), "trace": traceback.format_exc()}},
            }
