import uuid
from decimal import Decimal
from typing import Protocol


class PaymentProviderError(Exception):
    """A payment provider's API call failed or returned an unexpected
    shape. Each provider module raises this rather than its own
    provider-specific exception type, so calling code (checkout, the
    webhook handler) can handle "the gateway broke" once, generically,
    without knowing which specific gateway was involved."""


def generate_tx_ref() -> str:
    """Not provider-specific — this is Yeneb's own internal payment
    reference, the same format regardless of which gateway ends up
    handling it, so it lives here once rather than duplicated (or
    worse, formatted differently) in every provider module."""
    return f"yeneb-{uuid.uuid4().hex}"


class PaymentProvider(Protocol):
    """The shape every payment-gateway module in this package
    (chapa.py, and eventually telebirr.py/cbe.py/coopay.py once
    there's API access to build them) must expose. This is a
    structural Protocol, not a base class to inherit from — each
    provider stays a plain module of functions, matching how every
    other service in this codebase (app.services.sms, app.services.
    email, ...) is written, rather than introducing a class hierarchy
    that doesn't match the rest of the code. See
    app.services.payments.registry for how a provider module actually
    gets looked up by name.
    """

    #: Matches CheckoutRequest.payment_method's literal value for this
    #: provider (see app.schemas.order) and Order.payment_method once
    #: a payment through it completes.
    PROVIDER_NAME: str

    def is_configured(self) -> bool:
        """Whether this provider has real credentials set — same
        empty-by-default-until-configured pattern used everywhere else
        in app.core.config, so the test suite and local dev never
        require every gateway to be live to run."""
        ...

    def initialize_payment(
        self,
        *,
        tx_ref: str,
        amount: Decimal,
        first_name: str,
        last_name: str,
        email: str | None = None,
        phone_number: str | None = None,
    ) -> str | None:
        """Start a hosted-checkout payment. Returns the URL the payer
        should be redirected to, or None if this provider isn't
        configured (see is_configured)."""
        ...

    def verify_payment(self, tx_ref: str) -> dict:
        """The real, current status of a transaction, fetched directly
        from the provider — never trust a webhook payload alone as
        proof of payment; always re-verify through this first."""
        ...

    def verify_webhook_signature(self, raw_body: bytes, signature: str | None) -> bool:
        """Whether an incoming webhook request actually came from this
        provider."""
        ...
