"""
Stub payment provider client for local development and testing.

When PAYMENT_PROVIDER_STUB=true this client is returned by
get_provider_client() and all payment operations succeed without making
any network calls.  It is completely invisible when the flag is false.
"""
from __future__ import annotations

import logging
from typing import Any, Dict
from uuid import uuid4

from src.core.payment_provider.base import PaymentProviderClient

logger = logging.getLogger(__name__)


class StubProviderClient(PaymentProviderClient):
    """
    In-memory stub that always succeeds.

    Token details return a fake Visa card so that downstream code that
    reads brand/last4/exp_month/exp_year gets sensible values.

    Charge results return a deterministic-looking transaction id prefixed
    with "stub_txn_" so that logs and DB records are clearly identifiable
    as synthetic.
    """

    async def get_token_details(self, token: str, merchant_id: int = 0) -> Dict[str, Any]:
        """
        Return synthetic token details without any network call.

        Returns ``provider_payment_method_id`` (required by
        ``save_payment_method()``) plus optional card meta fields
        (``brand``, ``last4``, ``exp_month``, ``exp_year``).
        ``merchant_id`` is accepted for interface compatibility and ignored.
        """
        logger.info("StubProviderClient.get_token_details called for token=%s", token)
        return {
            "provider": "stub",
            "provider_payment_method_id": token,
            "brand": "visa",
            "last4": "4242",
            "exp_month": "12",
            "exp_year": "2027",
        }

    async def submit_charge(
        self,
        *,
        amount: float,
        currency: str,
        customer_id: int,
        merchant_id: int,
        token: str,
        payment_method_type: str = "card",
        capture: bool = True,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """
        Return a synthetic succeeded charge result without any network call.

        The returned dict matches the shape produced by
        `submit_payrix_charge()` in _lib/utils/payrix_transactions.py so
        that callers in payment_requests/services.py can use the result
        unchanged.
        """
        txn_id = f"stub_txn_{uuid4().hex[:12]}"
        logger.info(
            "StubProviderClient.submit_charge called: txn_id=%s amount=%s currency=%s "
            "customer_id=%s merchant_id=%s payment_method_type=%s",
            txn_id,
            amount,
            currency,
            customer_id,
            merchant_id,
            payment_method_type,
        )
        return {
            "transaction_id": txn_id,
            "status": "succeeded",
            "amount": amount,
            "currency": currency,
            "raw_response": {
                "id": txn_id,
                "status": "approved",
                "amount": amount,
                "currency": currency,
            },
        }
