"""
Grubtech Order Status Update - Python

This example demonstrates how to update order status in Grubtech.

Prerequisites:
- Python 3.8+
- requests library (pip install requests)
- Valid access token from authentication

Replace the following placeholders:
- {{AUTH_TOKEN}}: Access token from authentication step
- {{ORDER_ID}}: The Grubtech order ID to update
- {{NEW_STATUS}}: The new status value
"""

import requests
import sys
from datetime import datetime
from enum import Enum
from typing import Dict, Any, Optional

AUTH_TOKEN = '{{AUTH_TOKEN}}'
BASE_URL = 'https://api.staging.grubtech.io'


class OrderStatus(Enum):
    """Valid order status values"""
    ACCEPTED = 'accepted'
    PREPARING = 'preparing'
    READY = 'ready'
    DELIVERED = 'delivered'
    CANCELLED = 'cancelled'


def update_order_status(
    order_id: str,
    new_status: OrderStatus,
    notes: Optional[str] = None
) -> Dict[str, Any]:
    """
    Update order status in Grubtech

    Args:
        order_id: The Grubtech order ID
        new_status: The new status value
        notes: Optional notes about the status change

    Returns:
        Dict: Response from API

    Raises:
        Exception: If status update fails
    """
    try:
        # Construct status update payload
        payload = {
            'orderId': order_id,
            'status': new_status.value,
            'timestamp': datetime.utcnow().isoformat() + 'Z',
        }

        if notes:
            payload['notes'] = notes

        print(f'Updating order {order_id} to status: {new_status.value}')

        # Make status update request
        url = f'{BASE_URL}/v1/orders/{order_id}/status'
        headers = {
            'Authorization': f'Bearer {AUTH_TOKEN}',
            'Content-Type': 'application/json',
        }

        response = requests.put(url, json=payload, headers=headers, timeout=10)

        # Check for errors
        if not response.ok:
            raise Exception(
                f'Status update failed: {response.status_code} - {response.text}'
            )

        # Parse response
        data = response.json()

        print(f'✅ Order status updated successfully!')
        print(f'Order ID: {data["orderId"]}')
        print(f'New Status: {data["status"]}')
        print(f'Updated At: {data["updatedAt"]}')

        return data

    except requests.RequestException as e:
        print(f'❌ Status update error: {e}', file=sys.stderr)
        raise
    except Exception as e:
        print(f'❌ Unexpected error: {e}', file=sys.stderr)
        raise


def order_workflow_example(order_id: str) -> None:
    """
    Example: Update order through typical workflow

    Args:
        order_id: The Grubtech order ID
    """
    try:
        # Step 1: Accept the order
        update_order_status(order_id, OrderStatus.ACCEPTED, 'Order confirmed')

        # Step 2: Start preparing
        update_order_status(order_id, OrderStatus.PREPARING, 'Chef started cooking')

        # Step 3: Mark as ready
        update_order_status(order_id, OrderStatus.READY, 'Order ready for pickup')

        # Step 4: Mark as delivered
        update_order_status(order_id, OrderStatus.DELIVERED, 'Order delivered to customer')

        print('✅ Order workflow completed!')

    except Exception as e:
        print(f'❌ Workflow error: {e}', file=sys.stderr)

        # If something goes wrong, cancel the order
        update_order_status(order_id, OrderStatus.CANCELLED, 'Unable to fulfill order')


if __name__ == '__main__':
    try:
        order_id = '{{ORDER_ID}}'
        new_status = OrderStatus.PREPARING  # Change to {{NEW_STATUS}}

        # Single status update
        update_order_status(order_id, new_status, 'Status update from POS')

        # Or run through full workflow
        # order_workflow_example(order_id)

    except Exception as e:
        sys.exit(1)
