items = []

print("Enter each item name and price. Press Enter on a blank item name when done.")

while True:
	item_name = input("Item name: ").strip()
	if item_name == "":
		break

	person = input(f"Who ordered '{item_name}'? ").strip()
	if person == "":
		print("Person's name cannot be blank.")
		continue

	while True:
		entry = input(f"Price for {item_name}: ").strip()
		try:
			price = float(entry)
			if price < 0:
				print("Price cannot be negative.")
				continue
			items.append((item_name, price, person))
			break
		except ValueError:
			print("Please enter a valid number.")

if not items:
	print("No items entered.")
else:
	subtotal = sum(price for _, price, _ in items)

	while True:
		tip_input = input("What percent tip would you like to leave? ").strip().replace("%", "")
		try:
			tip_percent = float(tip_input)
			if tip_percent < 0:
				print("Tip percent cannot be negative.")
				continue
			break
		except ValueError:
			print("Please enter a valid tip percentage.")

	tip_amount = round(subtotal * (tip_percent / 100))
	total_bill = subtotal + tip_amount

	print("\nItemized bill:")
	for item_name, price, person in items:
		print(f"- {item_name}: ${price:.2f} ({person})")

	# Calculate per-person subtotals
	person_subtotals = {}
	for _, price, person in items:
		person_subtotals[person] = person_subtotals.get(person, 0) + price

	# Calculate per-person tip share (proportional)
	person_tips = {}
	for person, person_subtotal in person_subtotals.items():
		if subtotal > 0:
			person_tips[person] = tip_amount * (person_subtotal / subtotal)
		else:
			person_tips[person] = 0

	print("\nPer-person totals:")
	for person in person_subtotals:
		owed = person_subtotals[person] + person_tips[person]
		print(f"{person}: ${owed:.2f} (Subtotal: ${person_subtotals[person]:.2f}, Tip: ${person_tips[person]:.2f})")

	print(f"\nCheck subtotal: ${subtotal:.2f}")
	print(f"Tip ({tip_percent:.1f}%): ${tip_amount:.2f}")
	print(f"Final bill: ${total_bill:.2f}")
