items = []
diners = []

# ANSI color codes for terminal output
GREEN = "\033[92m"
RESET = "\033[0m"

def colored_input(prompt):
	return input(f"{GREEN}{prompt}{RESET}")

def section(title):
	print("\n" + "=" * 60)
	print(title)
	print("=" * 60)


section("DINER SETUP")
print("Enter diner names first.")
print("Press Enter on a blank name when done.")

while True:
	name = colored_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)
	print(f"Added diner: {name}")

if not diners:
	print("No diners entered.")
	raise SystemExit

section("ITEM ENTRY")
print("Enter each item name and price.")
print("Press Enter on a blank item name when done.")

item_number = 1
while True:
	print(f"\nItem #{item_number}")
	print("-" * 20)
	item_name = colored_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 = colored_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 = colored_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))
			print(f"Added: {item_name} (${price:.2f}) for {person}")
			item_number += 1
			break
		except ValueError:
			print("Please enter a valid number.")

if not items:
	print("No items entered.")
else:
	section("TIP")
	subtotal = sum(price for _, price, _ in items)
	print(f"Current subtotal: ${subtotal:.2f}")

	while True:
		tip_input = colored_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

	section("ITEMIZED 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

	section("PER-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})")

	section("FINAL TOTAL")
	print(f"Check subtotal: ${subtotal:.2f}")
	print(f"Tip ({tip_percent:.1f}%): ${tip_amount:.2f}")
	print(f"Final bill: ${total_bill:.2f}")
