items = []
diners = []

print("Enter diner names first. Press Enter on a blank name when done.")
while True:
	name = input("Diner name: ").strip()
	if name == "":
		break
	if name.lower() in (d.lower() for d in diners):
		print("That diner is already on the list.")
		continue
	diners.append(name)

if not diners:
	print("No diners entered.")
	raise SystemExit

print("\nEnter 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

	print("Who ordered it?")
	for i, diner in enumerate(diners, start=1):
		print(f"{i}. {diner}")

	while True:
		choice = input("Choose diner number: ").strip()
		if not choice.isdigit():
			print("Enter a valid number from the list.")
			continue
		index = int(choice)
		if index < 1 or index > len(diners):
			print("Number out of range.")
			continue
		person = diners[index - 1]
		break

	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}")
