from flask import Flask, request, jsonify, send_from_directory

app = Flask(__name__)

#id (int) -> { id (int), name (string), price (float), quantity (int) }
vending_machine = {
}

def get_current_id():
	if len(vending_machine) == 0:
		return 0
	else:
		return max( vending_machine.keys() )

# Define a route for the root URL ('/')
@app.route('/')
def index_page():
	return send_from_directory(".", "index.html")

# GET /item -> Returns all items as a list
@app.route('/item', methods=['GET'])
def get_items():
	# We convert the dictionary values to a list so the frontend gets an Array
	items_list = list(vending_machine.values())
	return jsonify(items_list)

# POST /item -> Creates a new item
@app.route('/item', methods=['POST'])
def create_item():
	current_id = get_current_id()
	data = request.json
	
	# Simple validation
	if not 'name' in data or not 'price' in data or not 'quantity' in data:
		return jsonify({"error": "Missing name, price, or quantity"}), 400

	current_id += 1
	new_item = {
		"id": current_id,
		"name": data['name'],
		"price": float(data['price']),
		"quantity": int(data['quantity'])
	}
	
	vending_machine[current_id] = new_item
	return jsonify(new_item), 201

# PUT /item/:id/buy -> Reduces quantity by one
@app.route('/item/<int:item_id>/buy', methods=['PUT'])
def buy_item(item_id):
	if item_id not in vending_machine:
		return jsonify({"error": "Item not found"}), 404

	item = vending_machine[item_id]

	# LOGIC CHECK: Can't buy if stock is 0
	if item['quantity'] <= 0:
		return jsonify({"error": "Out of stock"}), 400

	item['quantity'] -= 1
	return jsonify(item)

# PUT /item/:id/restock -> Updates quantity by a specific amount
@app.route('/item/<int:item_id>/restock', methods=['PUT'])
def restock_item(item_id):
	if item_id not in vending_machine:
		return jsonify({"error": "Item not found"}), 404

	data = request.json
	
	# We expect JSON like: { "amount": 5 }
	if 'amount' not in data:
		return jsonify({"error": "Missing 'amount' in body"}), 400
		
	amount_to_add = int(data['amount'])
	
	item = vending_machine[item_id]
	item['quantity'] += amount_to_add
	
	return jsonify(item)

if __name__ == '__main__':
	app.run(debug=True, port=5000)
