"""
VNPAY Payment Gateway Integration for AutoLyrics OneClick
Supports VNPAY-QR, Local ATM (Napas), and International Visa/Mastercard
"""

import hmac
import hashlib
import urllib.parse
from datetime import datetime

class VNPay:
    def __init__(self, tmn_code, hash_secret, payment_url, return_url):
        self.tmn_code = tmn_code
        self.hash_secret = hash_secret
        self.payment_url = payment_url
        self.return_url = return_url

    def build_payment_url(self, order_id, amount_vnd, order_desc, client_ip):
        """
        Build secure VNPAY checkout URL with HMAC-SHA512 signature.
        amount_vnd: integer in VND (e.g., 75000 for $2.99)
        """
        create_date = datetime.now().strftime('%Y%m%d%H%M%S')
        
        # VNPAY requires amount * 100
        vnp_amount = int(amount_vnd * 100)

        params = {
            'vnp_Version': '2.1.0',
            'vnp_Command': 'pay',
            'vnp_TmnCode': self.tmn_code,
            'vnp_Amount': str(vnp_amount),
            'vnp_CurrCode': 'VND',
            'vnp_TxnRef': str(order_id),
            'vnp_OrderInfo': order_desc,
            'vnp_OrderType': 'billpayment',
            'vnp_Locale': 'vn',
            'vnp_ReturnUrl': self.return_url,
            'vnp_IpAddr': client_ip or '127.0.0.1',
            'vnp_CreateDate': create_date,
        }

        # 1. Sort parameters A-Z by key
        sorted_params = sorted(params.items())

        # 2. Build query string for hash and URL
        hash_data = []
        for key, val in sorted_params:
            if val is not None and len(str(val)) > 0:
                hash_data.append(f"{urllib.parse.quote_plus(key)}={urllib.parse.quote_plus(str(val))}")

        query_string = '&'.join(hash_data)

        # 3. Create HMAC-SHA512 checksum
        secure_hash = hmac.new(
            self.hash_secret.encode('utf-8'),
            query_string.encode('utf-8'),
            hashlib.sha512
        ).hexdigest()

        return f"{self.payment_url}?{query_string}&vnp_SecureHash={secure_hash}"

    def validate_response(self, query_params):
        """
        Verify VNPAY return response signature.
        query_params: dict of GET parameters received from VNPAY
        """
        received_hash = query_params.get('vnp_SecureHash', '')
        
        # Filter out hash parameters
        data = {}
        for key, val in query_params.items():
            if key not in ['vnp_SecureHash', 'vnp_SecureHashType']:
                data[key] = val

        # Sort and build hash string
        sorted_params = sorted(data.items())
        hash_data = []
        for key, val in sorted_params:
            if val is not None and len(str(val)) > 0:
                hash_data.append(f"{urllib.parse.quote_plus(key)}={urllib.parse.quote_plus(str(val))}")

        query_string = '&'.join(hash_data)

        computed_hash = hmac.new(
            self.hash_secret.encode('utf-8'),
            query_string.encode('utf-8'),
            hashlib.sha512
        ).hexdigest()

        is_valid = computed_hash.lower() == received_hash.lower()
        response_code = query_params.get('vnp_ResponseCode', '')
        is_success = is_valid and response_code == '00'

        return {
            'is_valid': is_valid,
            'is_success': is_success,
            'response_code': response_code,
            'order_id': query_params.get('vnp_TxnRef', ''),
            'amount_vnd': int(query_params.get('vnp_Amount', '0')) // 100,
            'vnp_transaction_no': query_params.get('vnp_TransactionNo', '')
        }
