"""
FreeExile Platform Payment Compliance Router.
Enforces Apple App Store Guideline 3.1.1 and Google Play Billing requirements.
Guarantees iOS and Google Play builds never expose unauthorized payment processors,
while Web/PC and Sideload builds offer complete gateway flexibility including Web3 Crypto.
"""

import uuid
from enum import Enum
from typing import Dict, List, Optional
from dataclasses import dataclass


class PlatformType(str, Enum):
    PLATFORM_UNKNOWN = "PLATFORM_UNKNOWN"
    PLATFORM_IOS = "PLATFORM_IOS"
    PLATFORM_ANDROID_PLAYSTORE = "PLATFORM_ANDROID_PLAYSTORE"
    PLATFORM_ANDROID_SIDELOAD = "PLATFORM_ANDROID_SIDELOAD"
    PLATFORM_WEB_PC = "PLATFORM_WEB_PC"
    PLATFORM_MACOS_DIRECT = "PLATFORM_MACOS_DIRECT"


class PaymentGateway(str, Enum):
    GATEWAY_UNKNOWN = "GATEWAY_UNKNOWN"
    GATEWAY_APPLE_IAP = "GATEWAY_APPLE_IAP"
    GATEWAY_GOOGLE_PLAY = "GATEWAY_GOOGLE_PLAY"
    GATEWAY_STRIPE = "GATEWAY_STRIPE"
    GATEWAY_PAYPAL = "GATEWAY_PAYPAL"
    GATEWAY_CRYPTO_WEB3 = "GATEWAY_CRYPTO_WEB3"
    GATEWAY_LOCAL_VIETNAM = "GATEWAY_LOCAL_VIETNAM"


class PlatformPolicyViolationError(Exception):
    """Raised when an unauthorized gateway is requested for a compliant platform build."""
    pass


@dataclass(slots=True, frozen=True)
class PaymentMethodOption:
    gateway: PaymentGateway
    display_name: str
    icon_url: str
    is_recommended: bool = False
    bonus_coin_multiplier: float = 1.0


class PaymentGatewayRouter:
    """Authoritative Router for Cross-Platform Payment Policy Compliance."""

    def get_allowed_payment_methods(
        self,
        platform: PlatformType,
        country_code: str = "US"
    ) -> List[PaymentMethodOption]:
        """
        Returns authorized payment methods strictly compliant with platform store guidelines.
        """
        # 1. APPLE IOS (App Store Guideline 3.1.1)
        if platform == PlatformType.PLATFORM_IOS:
            return [
                PaymentMethodOption(
                    gateway=PaymentGateway.GATEWAY_APPLE_IAP,
                    display_name="Apple In-App Purchase (StoreKit 2)",
                    icon_url="assets/icons/payment_apple_pay.png",
                    is_recommended=True,
                    bonus_coin_multiplier=1.0
                )
            ]

        # 2. GOOGLE PLAY STORE (Google Play In-App Billing Policy)
        if platform == PlatformType.PLATFORM_ANDROID_PLAYSTORE:
            return [
                PaymentMethodOption(
                    gateway=PaymentGateway.GATEWAY_GOOGLE_PLAY,
                    display_name="Google Play Billing",
                    icon_url="assets/icons/payment_google_play.png",
                    is_recommended=True,
                    bonus_coin_multiplier=1.0
                )
            ]

        # 3. WEB TOP-UP PORTAL / DIRECT PC / APK SIDELOAD
        methods = [
            PaymentMethodOption(
                gateway=PaymentGateway.GATEWAY_CRYPTO_WEB3,
                display_name="Web3 Crypto Wallet (MetaMask / Phantom / USDT / ETH)",
                icon_url="assets/icons/payment_web3_crypto.png",
                is_recommended=True,
                bonus_coin_multiplier=1.10 # +10% Extra Coins
            ),
            PaymentMethodOption(
                gateway=PaymentGateway.GATEWAY_STRIPE,
                display_name="Credit / Debit Card (Stripe)",
                icon_url="assets/icons/payment_stripe.png",
                is_recommended=False,
                bonus_coin_multiplier=1.10 # +10% Extra Coins
            ),
            PaymentMethodOption(
                gateway=PaymentGateway.GATEWAY_PAYPAL,
                display_name="PayPal Global",
                icon_url="assets/icons/payment_paypal.png",
                is_recommended=False,
                bonus_coin_multiplier=1.05
            ),
        ]

        if country_code.upper() == "VN":
            methods.append(PaymentMethodOption(
                gateway=PaymentGateway.GATEWAY_LOCAL_VIETNAM,
                display_name="MoMo / VNPay / Chuyển Khoản Ngân Hàng QR",
                icon_url="assets/icons/payment_vnpay_momo.png",
                is_recommended=False,
                bonus_coin_multiplier=1.10
            ))

        return methods

    def create_payment_order(
        self,
        account_id: str,
        product_id: str,
        platform: PlatformType,
        requested_gateway: PaymentGateway,
        country_code: str = "US"
    ) -> str:
        """
        Validates request compliance before issuing order_id.
        Throws PlatformPolicyViolationError if attempting prohibited gateway bypass.
        """
        allowed_methods = self.get_allowed_payment_methods(platform, country_code)
        allowed_gateways = {m.gateway for m in allowed_methods}

        if requested_gateway not in allowed_gateways:
            raise PlatformPolicyViolationError(
                f"Platform '{platform.value}' strictly forbids gateway '{requested_gateway.value}'. "
                f"Allowed gateways: {[g.value for g in allowed_gateways]}"
            )

        order_id = f"ord_{platform.name.lower()[:3]}_{uuid.uuid4().hex[:12]}"
        return order_id
