from typing import Optional
import requests
from logging import getLogger
from config.settings import DEVELOPMENT
from models.sales import OrderWeb, ItemWeb
from services.data_service import DataServiceFactory
from models.items import Order
from enums.locations import Locations

logger = getLogger(__name__)
user_data_service = DataServiceFactory.get_user_service()
is_habilited_hexagon = False
beers_habilited = []
def get_printer_url(location: Locations, table_number: int , products: list[str] = []) -> str:
    if DEVELOPMENT:
        return "http://localhost:5004"
    if location == Locations.BAR:
        if is_habilited_hexagon and table_number >= 500 and set(products).issubset(set(beers_habilited)):
            return "http://10.10.12.15:5004"
        else:
            return "http://10.10.12.11:5004"
    elif location == Locations.COCTELERY:
        return "http://10.10.12.12:5004"
    elif location == Locations.PIZZAS:
        return "http://10.10.12.13:5004"
    else:
        return "http://10.10.12.14:5004"

def print_order(order: Order, location:Locations ):
    """Send order to printer"""
    logger.info(f"Attempting to print order for table {order.table}")
    products = list(map(lambda x: x.name, order.items))

    printer_url = get_printer_url(location, order.table, products)

    try:
        if not order.items or not order.table:
            error_msg = "Order must have items and a table number"
            logger.error(error_msg)
            
            raise ValueError(error_msg)
        
        # Prepare the order data for printing
        order_data = {
            "table": order.table,
            "items": [{"name": item.name, "price": item.price, "quantity": item.quantity, "comment": item.comment} for item in order.items],
            "customerName": order.customerName,
            "totalAmount": order.totalAmount,
            "orderDate": order.orderDate
        }
        
        logger.info(f"Order data prepared for printing: table={order.table}, items={order.items}, total={order.totalAmount}")
        

        # Send the order data to the printer service
        response = requests.post(
            f"{printer_url}/print", 
            json=order_data, 
            headers={"Authorization": f"Bearer PRINTER123cerveza@"},
            timeout=10
        )

        if response.status_code != 200:
            error_msg = f"Failed to print order: HTTP {response.status_code} - {response.text}"
            logger.error(error_msg)
            
            raise Exception(error_msg)

        logger.info(f"Order printed successfully for table {order.table}")
        
        return response.json()  # Return the response from the printer service
        
    except requests.RequestException as e:
        error_msg = f"Network error while printing order for table {order.table}: {e}"
        logger.error(error_msg)
        
        raise Exception(error_msg)
    except Exception as e:
        error_msg = f"Unexpected error while printing order for table {order.table}: {e}"
        logger.error(error_msg)
        
        raise

def print_ticket(number_table: int):
    """Send a ticket to the printer"""
    logger.info(f"Attempting to print ticket for table {number_table}")
    printer_url = get_printer_url(Locations.BAR, number_table)
    try:

        
        response = requests.get(
            f"{printer_url}/ticket/{number_table}", 
            headers={"Authorization": f"Bearer PRINTER123cerveza@"},
            timeout=10
        )

        if response.status_code != 200:
            error_msg = f"Failed to print ticket for table {number_table}: HTTP {response.status_code} - {response.text}"
            logger.error(error_msg)
            
            raise Exception(error_msg)

        logger.info(f"Ticket printed successfully for table {number_table}")
        
        
        return response.json()  # Return the response from the printer service
        
    except requests.RequestException as e:
        error_msg = f"Network error while printing ticket for table {number_table}: {e}"
        logger.error(error_msg)
        raise Exception(error_msg)
    except Exception as e:
        error_msg = f"Unexpected error while printing ticket for table {number_table}: {e}"
        logger.error(error_msg)
        
        raise



def get_status(location: Locations):
    """Get the status of the printer service"""
    logger.info("Checking printer service status")
    
    printer_url = get_printer_url(location, 1)

    try:
        response = requests.get(
            f"{printer_url}/status", 
            headers={"Authorization": f"Bearer PRINTER123cerveza@"},
            timeout=10
        )
        
        data = response.json()
        status = data.get("printer_connected", False)
        
        logger.info(f"Printer service status: {'online' if status else 'offline'}")
        
        
        return bool(status)
        
    except requests.RequestException as e:
        error_msg = f"Error connecting to printer service: {e}"
        logger.error(error_msg)

        return False
    except Exception as e:
        error_msg = f"Unexpected error checking printer status: {e}"
        logger.error(error_msg)
        
        return False

