"""
Atmos internal webhook handler.
"""
import json
import hashlib
import logging
import threading

from django.views import View
from django.conf import settings
from django.http import JsonResponse
from django.utils.module_loading import import_string

from paytechuz.integrations.django.models import PaymentTransaction
from paytechuz.license import LicenseManager


logger = logging.getLogger(__name__)


class AtmosWebhook(View):
    """
    Base Atmos webhook handler for Django.

    This class handles webhook requests from the Atmos payment system.
    You can extend this class and override the event methods to customize
    the behavior.
    """
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # Validate license
        LicenseManager.validate_license_api_key()

        atmos_settings = settings.PAYTECHUZ.get('ATMOS', {})

        self.api_key = atmos_settings.get('API_KEY', '')

        account_model_path = atmos_settings.get('ACCOUNT_MODEL')
        try:
            self.account_model = import_string(account_model_path)
        except ImportError:
            logger.error(
                "Could not import %s. Check PAYTECHUZ.ATMOS.ACCOUNT_MODEL setting.",
                account_model_path
            )
            # Raise if critical or allow to continue if not strictly needed immediately
            if account_model_path:
                raise ImportError(f"Import error: {account_model_path}") from None

        self.account_field = atmos_settings.get('ACCOUNT_FIELD', 'id')

    def post(self, request, **_):
        """
        Handle POST requests from Atmos.
        """
        try:
            # Parse request data
            data = json.loads(request.body.decode('utf-8'))

            # Verify signature
            received_signature = data.get('sign', '')
            if not self._verify_signature(data, received_signature):
                logger.error("Invalid webhook signature")
                return JsonResponse({
                    'status': 0,
                    'message': 'Invalid signature'
                }, status=400)

            # Extract webhook data
            # store_id = data.get('store_id') # unused
            transaction_id = data.get('transaction_id')
            # amount = data.get('amount') # unused
            invoice = data.get('invoice')
            # transaction_time = data.get('transaction_time') # unused

            logger.info(f"Webhook received for transaction {transaction_id}, invoice {invoice}")

            # Find transaction by invoice (account)
            try:
                transaction = PaymentTransaction._default_manager.get(
                    gateway=PaymentTransaction.ATMOS,
                    account_id=invoice
                )

                # Update transaction with webhook data
                transaction.transaction_id = transaction_id
                transaction.mark_as_paid()

                # Decrement usage limit in background (non-blocking)
                LicenseManager.decrement_usage_limit_async()

                # Call the event method
                self.successfully_payment(data, transaction)

                return JsonResponse({
                    'status': 1,
                    'message': 'Успешно'
                })

            except PaymentTransaction.DoesNotExist:
                logger.error(f"Transaction not found for invoice: {invoice}")
                return JsonResponse({
                    'status': 0,
                    'message': f'Transaction not found for invoice: {invoice}'
                }, status=400)

        except Exception as e:
            logger.exception("Unexpected error in Atmos webhook: %s", e)
            return JsonResponse({
                'status': 0,
                'message': f'Error: {str(e)}'
            }, status=500)

    def _verify_signature(self, webhook_data, received_signature):
        """
        Verify webhook signature from Atmos.
        """
        store_id = str(webhook_data.get('store_id', ''))
        transaction_id = str(webhook_data.get('transaction_id', ''))
        invoice = str(webhook_data.get('invoice', ''))
        amount = str(webhook_data.get('amount', ''))

        signature_string = f"{store_id}{transaction_id}{invoice}{amount}{self.api_key}"
        calculated_signature = hashlib.md5(signature_string.encode('utf-8')).hexdigest()

        return calculated_signature == received_signature

    # Event hooks
    def successfully_payment(self, params, transaction): pass
    def cancelled_payment(self, params, transaction): pass

