import random
import requests

API_URL = "http://127.0.0.1:8000"
USER_ID = 1  # Cambia esto por el id de usuario válido si es necesario

# Utilidad para obtener todos los productos con sus ids desde la API
# (esto requiere que el backend esté corriendo y tenga productos cargados)
def get_products():
    resp = requests.get(f"{API_URL}/products")
    if resp.status_code == 200:
        return resp.json()
    else:
        print("Error obteniendo productos:", resp.status_code, resp.text)
        return []

def create_single_order(product_list):
    available_products = [(prod['id'], prod['name']) for prod in product_list]
    num_unique_products = random.choices([2, 3, 4, 5, 6, 7, 8], weights=[30, 30, 30, 10, 3, 1, 1])[0]
    selected_products = random.sample(available_products, k=min(num_unique_products, len(available_products)))
    order_products = []
    for product_id, prod_name in selected_products:
        quantity = random.choices([1, 2, 3, 4, 5, 6], weights=[45, 30, 15, 7, 2, 1])[0]
        order_products.append({"product_id": product_id, "quantity": quantity})
    return order_products

def create_multiple_orders(user_id, n_orders=None, algorithm="least-loaded", random_seed=46):
    product_list = get_products()
    if not product_list:
        print("No hay productos disponibles para crear órdenes.")
        return
    if n_orders is None:
        n_orders = 50
    print(f"Generando {n_orders} órdenes...")
    random.seed(random_seed)
    for i in range(n_orders):
        order_products = create_single_order(product_list)
        table_id = random.randint(1, 20)  # Número de mesa aleatorio entre 1 y 20
        order_data = {
            "products": order_products,
            "table_id": table_id,
            "algorithm": algorithm
        }
        resp = requests.post(f"{API_URL}/orders", json=order_data)
        if resp.status_code in (200, 201):
            print(f"Orden {i+1} creada correctamente para la mesa {table_id}.")
        else:
            print(f"Error creando orden {i+1}: {resp.status_code} {resp.text}")

def delete_all_orders():
    resp = requests.get(f"{API_URL}/orders")
    if resp.status_code == 200:
        orders = resp.json()
        for order in orders:
            order_id = order['id']
            del_resp = requests.delete(f"{API_URL}/orders/{order_id}/")
            if del_resp.status_code == 200:
                print(f"Orden {order_id} eliminada.")
            else:
                print(f"Error eliminando orden {order_id}: {del_resp.status_code} {del_resp.text}")
    else:
        print("Error obteniendo órdenes para eliminar:", resp.status_code, resp.text)

if __name__ == "__main__":
    create_multiple_orders(user_id=None, random_seed=42)