"""
Grubtech Order Receive Webhook - Python (Flask)

This example demonstrates how to receive orders from Grubtech
via webhook and process them in your system.

Prerequisites:
- Python 3.8+
- Flask (pip install flask)

Replace the following placeholders:
- {{WEBHOOK_SECRET}}: Your webhook secret for signature verification
- {{ORDER_PROCESSING_LOGIC}}: Your business logic to process the order
"""

from flask import Flask, request, jsonify
import hmac
import hashlib
import time
from datetime import datetime, timedelta
from typing import Dict, Any, List

app = Flask(__name__)
WEBHOOK_SECRET = '{{WEBHOOK_SECRET}}'


def verify_signature(data: bytes, signature: str) -> bool:
    """
    Verify webhook signature using HMAC-SHA256

    Args:
        data: Raw request body
        signature: Signature from X-Grubtech-Signature header

    Returns:
        bool: True if signature is valid
    """
    if not signature:
        print('❌ No signature provided')
        return False

    # Calculate expected signature
    expected_signature = hmac.new(
        WEBHOOK_SECRET.encode('utf-8'),
        data,
        hashlib.sha256
    ).hexdigest()

    # Constant-time comparison
    is_valid = hmac.compare_digest(signature, expected_signature)

    if not is_valid:
        print('❌ Invalid signature')

    return is_valid


def process_order(order: Dict[str, Any]) -> Dict[str, Any]:
    """
    Process order (replace with your business logic)

    Args:
        order: Order data from webhook

    Returns:
        Dict: Response to send back to Grubtech
    """
    try:
        order_id = order['orderId']
        customer_name = order['customer']['name']
        items_count = len(order['items'])
        total = order['totals']['total']

        print(f'📦 Processing order: {order_id}')
        print(f'Customer: {customer_name}')
        print(f'Items: {items_count}')
        print(f'Total: ${total}')

        # {{ORDER_PROCESSING_LOGIC}}
        # Example: Save to database, notify kitchen, etc.

        # Simulate processing
        time.sleep(0.1)

        # Calculate estimated ready time (30 minutes from now)
        ready_time = (datetime.utcnow() + timedelta(minutes=30)).isoformat() + 'Z'

        return {
            'accepted': True,
            'orderId': order_id,
            'partnerOrderId': f'POS-{int(time.time())}',
            'message': 'Order accepted successfully',
            'estimatedReadyTime': ready_time,
        }

    except Exception as e:
        print(f'❌ Order processing error: {e}')

        return {
            'accepted': False,
            'orderId': order.get('orderId', 'unknown'),
            'message': f'Order rejected: {str(e)}',
        }


@app.route('/webhooks/grubtech/orders', methods=['POST'])
def receive_order():
    """
    Webhook endpoint to receive orders from Grubtech
    """
    try:
        # Get raw request data and signature
        raw_data = request.get_data()
        signature = request.headers.get('X-Grubtech-Signature', '')

        # Verify signature
        if not verify_signature(raw_data, signature):
            return jsonify({
                'accepted': False,
                'message': 'Invalid signature',
            }), 401

        # Parse order data
        order = request.get_json()

        # Validate order data
        if not order.get('orderId') or not order.get('items') or len(order['items']) == 0:
            return jsonify({
                'accepted': False,
                'message': 'Invalid order data',
            }), 400

        # Process order
        response = process_order(order)

        # Send response
        status_code = 200 if response['accepted'] else 400
        return jsonify(response), status_code

    except Exception as e:
        print(f'❌ Webhook error: {e}')
        return jsonify({
            'accepted': False,
            'message': 'Internal server error',
        }), 500


@app.route('/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({'status': 'ok'})


if __name__ == '__main__':
    print('✅ Webhook server starting...')
    print('Webhook URL: http://localhost:5000/webhooks/grubtech/orders')
    app.run(host='0.0.0.0', port=5000, debug=True)
