import hashlib
import hmac
import time
import uuid
from typing import Any, Optional
import httpx
from core.config import get_settings
from core.exceptions import PaymentError
from core.logging import get_logger
from infrastructure.payments.gateways.base import PaymentGateway

logger = get_logger(__name__)


class StripeGateway(PaymentGateway):
    """
    Stripe payment gateway implementation.
    Supports Checkout Session creation, webhook signature verification, and refunds.
    """

    def __init__(
        self,
        secret_key: Optional[str] = None,
        webhook_secret: Optional[str] = None,
    ):
        settings = get_settings()
        self.secret_key = secret_key or settings.STRIPE_SECRET_KEY or "sk_test_mock_secret"
        self.webhook_secret = webhook_secret or settings.STRIPE_WEBHOOK_SECRET or "whsec_mock_secret"
        self.base_url = "https://api.stripe.com/v1"

    async def create_order(
        self,
        amount: int,
        currency: str,
        receipt: str,
        notes: dict[str, Any],
        idempotency_key: Optional[str] = None,
    ) -> dict[str, Any]:
        """
        Creates a Stripe Checkout Session or Payment Intent.
        """
        if self.secret_key.startswith("sk_test_placeholder") or self.secret_key.startswith("sk_test_mock"):
            mock_session_id = f"cs_test_{uuid.uuid4().hex[:20]}"
            return {
                "id": mock_session_id,
                "object": "checkout.session",
                "amount_total": amount,
                "currency": currency.lower(),
                "client_reference_id": receipt,
                "payment_status": "unpaid",
                "status": "open",
                "metadata": notes,
                "url": f"https://checkout.stripe.com/c/pay/{mock_session_id}",
            }

        headers = {
            "Authorization": f"Bearer {self.secret_key}",
            "Content-Type": "application/x-www-form-urlencoded",
        }
        if idempotency_key:
            headers["Idempotency-Key"] = idempotency_key

        data = {
            "payment_method_types[0]": "card",
            "line_items[0][price_data][currency]": currency.lower(),
            "line_items[0][price_data][unit_amount]": str(amount),
            "line_items[0][price_data][product_data][name]": notes.get("plan_name", "Telegram SaaS Subscription"),
            "line_items[0][quantity]": "1",
            "mode": "payment",
            "client_reference_id": receipt,
            "success_url": "https://dashboard.domain.com/billing?success=true&session_id={CHECKOUT_SESSION_ID}",
            "cancel_url": "https://dashboard.domain.com/billing?canceled=true",
        }

        async with httpx.AsyncClient(timeout=15.0) as client:
            try:
                resp = await client.post(f"{self.base_url}/checkout/sessions", data=data, headers=headers)
                if resp.status_code not in (200, 201):
                    logger.error("stripe_checkout_failed", status_code=resp.status_code, body=resp.text)
                    raise PaymentError(f"Stripe checkout session creation failed: {resp.text}")
                return resp.json()
            except httpx.RequestError as exc:
                logger.error("stripe_network_error", error=str(exc))
                raise PaymentError(f"Network error connecting to Stripe: {exc}")

    def verify_payment_signature(
        self,
        order_id: str,
        payment_id: str,
        signature: str,
    ) -> bool:
        """
        For Stripe, client sends session_id and payment_intent_id.
        Verifies non-empty IDs or client verification token.
        """
        if not order_id or not payment_id:
            return False
        # If client passes signature, verify HMAC of session_id + payment_id with secret_key
        if signature:
            expected = hmac.new(
                self.secret_key.encode("utf-8"),
                f"{order_id}|{payment_id}".encode("utf-8"),
                hashlib.sha256,
            ).hexdigest()
            return hmac.compare_digest(expected, signature)
        return True

    def verify_webhook_signature(
        self,
        payload: bytes,
        signature: str,
        headers: Optional[dict[str, str]] = None,
    ) -> bool:
        """
        Verifies incoming Stripe-Signature header.
        Format: 't=1614555555,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd'
        """
        if not payload or not signature:
            return False

        try:
            parts = dict(item.split("=", 1) for item in signature.split(","))
            timestamp = parts.get("t")
            v1_signature = parts.get("v1")

            if not timestamp or not v1_signature:
                return False

            signed_payload = f"{timestamp}.".encode("utf-8") + payload
            computed_signature = hmac.new(
                self.webhook_secret.encode("utf-8"),
                signed_payload,
                hashlib.sha256,
            ).hexdigest()

            return hmac.compare_digest(computed_signature, v1_signature)
        except Exception as exc:
            logger.warning("stripe_signature_parsing_failed", error=str(exc))
            return False

    async def create_refund(
        self,
        payment_id: str,
        amount: int,
        currency: str,
        reason: str,
    ) -> dict[str, Any]:
        """
        Issues a Stripe refund against a Charge or PaymentIntent.
        """
        if self.secret_key.startswith("sk_test_placeholder") or self.secret_key.startswith("sk_test_mock"):
            return {
                "id": f"re_test_{uuid.uuid4().hex[:20]}",
                "object": "refund",
                "amount": amount,
                "currency": currency.lower(),
                "payment_intent": payment_id,
                "status": "succeeded",
                "reason": "requested_by_customer",
            }

        headers = {
            "Authorization": f"Bearer {self.secret_key}",
            "Content-Type": "application/x-www-form-urlencoded",
        }
        data = {
            "payment_intent": payment_id,
            "amount": str(amount),
            "reason": "requested_by_customer",
        }

        async with httpx.AsyncClient(timeout=15.0) as client:
            try:
                resp = await client.post(f"{self.base_url}/refunds", data=data, headers=headers)
                if resp.status_code not in (200, 201):
                    logger.error("stripe_refund_failed", status_code=resp.status_code, body=resp.text)
                    raise PaymentError(f"Stripe refund failed: {resp.text}")
                return resp.json()
            except httpx.RequestError as exc:
                logger.error("stripe_refund_network_error", error=str(exc))
                raise PaymentError(f"Network error processing Stripe refund: {exc}")
