# File Handling Mini Project — Shopping List
# persistent shopping list — saves to CSV on quit, loads on start
# redhorndev.com

import csv

FILENAME = "shopping_list.csv"
shopping = {}

# ─────────────────────────────────────────────
# Load — read CSV into dict on start
# ─────────────────────────────────────────────

def load(filename):
    try:
        with open(filename, "r", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            for row in reader:
                shopping[row["name"]] = {
                    "qty":   int(row["qty"]),
                    "price": float(row["price"])
                }
    except FileNotFoundError:
        pass    # first run — no file yet, start empty

# ─────────────────────────────────────────────
# Save — write dict to CSV on quit
# ─────────────────────────────────────────────

def save(filename, data):
    with open(filename, "w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=["name", "qty", "price"])
        writer.writeheader()
        for name, d in data.items():
            writer.writerow({"name": name, "qty": d["qty"], "price": d["price"]})

# ─────────────────────────────────────────────
# Helper — print current list
# ─────────────────────────────────────────────

def print_list(d):
    if not d:
        print("Your list is empty.")
    else:
        print("\nYour list:")
        for item, data in d.items():
            subtotal = data["qty"] * data["price"]
            print(f"- {item:<10} x{data['qty']}   ${subtotal:.2f}")

# ─────────────────────────────────────────────
# Load on start
# ─────────────────────────────────────────────

load(FILENAME)

# ─────────────────────────────────────────────
# Main loop
# ─────────────────────────────────────────────

while True:
    print("\n1 — Add item")
    print("2 — Remove item")
    print("3 — View list")
    print("4 — Checkout")
    print("5 — Quit")
    choice = input("Your choice: ")

    if choice == "1":
        name  = input("Item name: ").capitalize()
        qty   = int(input("Quantity: "))
        price = float(input("Price per unit: $"))
        shopping[name] = {"qty": qty, "price": price}
        print("Added.")

    elif choice == "2":
        name = input("Item to remove: ").capitalize()
        if name in shopping:
            shopping.pop(name)
            print(f"{name} removed.")
        else:
            print(f'"{name}" is not on your list.')

    elif choice == "3":
        print_list(shopping)

    elif choice == "4":
        if not shopping:
            print("Your list is empty.")
        else:
            print("\n--- Checkout ---")
            total = 0
            for item, data in shopping.items():
                subtotal = data["qty"] * data["price"]
                total += subtotal
                print(f"{item:<10} x{data['qty']}   ${subtotal:.2f}")
            print(f"Total:         ${total:.2f}")

    elif choice == "5":
        save(FILENAME, shopping)
        print("List saved. Out.")
        break

    else:
        print("Invalid choice. Enter 1 to 5.")
