"""
Screencast material for Chapter 6 (named-rubric code review).

Milestone 1 of the expense tracker: add an expense, list expenses, show a total.
Written deliberately at realistic junior level — it works, but a review has plenty
to say about it. Do not clean it up before recording.

Run:  python expense-tracker-m1.py
"""

import json
import os

FILE = "expenses.json"


def load():
    if os.path.exists(FILE):
        f = open(FILE)
        data = json.load(f)
        return data
    else:
        return []


def save(data):
    f = open(FILE, "w")
    json.dump(data, f)


def add(desc, amount, category):
    data = load()
    data.append({"desc": desc, "amount": float(amount), "category": category})
    save(data)
    print("added!")


def list_all():
    data = load()
    for i in range(len(data)):
        print(str(i) + ". " + data[i]["desc"] + " - " + str(data[i]["amount"]) +
              " (" + data[i]["category"] + ")")


def total():
    data = load()
    t = 0
    for d in data:
        t = t + d["amount"]
    print("Total: " + str(t))


def main():
    while True:
        cmd = input("> ")
        if cmd == "add":
            d = input("description: ")
            a = input("amount: ")
            c = input("category: ")
            add(d, a, c)
        elif cmd == "list":
            list_all()
        elif cmd == "total":
            total()
        elif cmd == "quit":
            break
        else:
            print("unknown command")


main()

# Issues a good named-rubric review should surface (for the presenter's reference —
# do NOT read these out; let the review find them on camera):
#
# CORRECTNESS   float(amount) raises on non-numeric input, crashing the loop
#               no handling of a corrupt/empty JSON file
# IDIOM         open() without a context manager (leaks handles, no flush guarantee)
#               range(len(data)) instead of enumerate()
#               string concatenation instead of f-strings
#               main() called at import time instead of under __main__ guard
# READABILITY   single-letter names (t, d, a, c, f)
#               functions print instead of returning — untestable
# EDGE CASES    empty list prints nothing with no message
#               money held as float, not Decimal
#               no rounding on the total
