import hashlib
import hmac
import logging
from decimal import Decimal

import httpx

from app.core.config import settings

logger = logging.getLogger("yeneb.chapa")

PROVIDER_NAME = "chapa"

_BASE_URL = "https://api.chapa.co/v1"


class ChapaError(Exception):
    """A Chapa API call failed or returned an unexpected shape."""


def is_configured() -> bool:
    return bool(settings.chapa_secret_key)


def initialize_payment(
    *,
    tx_ref: str,
    amount: Decimal,
    first_name: str,
    last_name: str,
    email: str | None = None,
    phone_number: str | None = None,
) -> str | None:
    """Start a Chapa hosted-checkout payment. Returns the checkout_url
    the customer should be redirected to, or None if Chapa isn't
    configured — same pattern as app.services.sms/email: only makes a
    real API call when chapa_secret_key is set, so the test suite
    (which exercises checkout) never hits the network.

    email and phone_number are both optional per Chapa's own docs
    (developer.chapa.co) — only amount, currency, and tx_ref are
    actually required, so a customer missing one or the other (see the
    User model docstring) can still pay via Chapa."""
    logger.info("Chapa payment initialized for %s: %s %s", tx_ref, amount, email)
    if not is_configured():
        return None

    payload = {
        "amount": str(amount),
        "currency": "ETB",
        "first_name": first_name,
        "last_name": last_name,
        "tx_ref": tx_ref,
        "callback_url": settings.chapa_callback_url,
        "return_url": settings.chapa_return_url,
    }
    if email:
        payload["email"] = email
    if phone_number:
        payload["phone_number"] = phone_number

    response = httpx.post(
        f"{_BASE_URL}/transaction/initialize",
        headers={"Authorization": f"Bearer {settings.chapa_secret_key}"},
        json=payload,
        timeout=15.0,
    )
    response.raise_for_status()
    data = response.json()
    checkout_url = data.get("checkout_url") or data.get("data", {}).get("checkout_url")
    if not checkout_url:
        raise ChapaError(f"Chapa initialize response missing checkout_url: {data}")
    return checkout_url


def verify_payment(tx_ref: str) -> dict:
    """GET the real, current status of a transaction from Chapa. Call
    this before trusting a webhook's payload — per Chapa's own
    documented best practice, a webhook is a notification trigger, not
    proof by itself."""
    response = httpx.get(
        f"{_BASE_URL}/transaction/verify/{tx_ref}",
        headers={"Authorization": f"Bearer {settings.chapa_secret_key}"},
        timeout=15.0,
    )
    response.raise_for_status()
    return response.json()


def verify_webhook_signature(raw_body: bytes, signature: str | None) -> bool:
    """HMAC-SHA256 of the raw request body against chapa_webhook_secret,
    compared to the x-chapa-signature header value. Constant-time
    compare to avoid leaking the correct signature through timing."""
    if not signature or not settings.chapa_webhook_secret:
        return False
    expected = hmac.new(
        settings.chapa_webhook_secret.encode(), raw_body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, signature)
