# Challenge 80 - Build a Study Tracker
import csv
from pathlib import Path

path = Path("study_sessions.csv")
subject = input("Subject: ").strip()
try:
    minutes = int(input("Minutes: "))
except ValueError:
    print("Minutes must be a whole number.")
else:
    if not subject or minutes <= 0:
        print("Subject and positive minutes are required.")
    else:
        need_header = not path.exists() or path.stat().st_size == 0
        with path.open("a", newline="", encoding="utf-8") as file:
            writer = csv.writer(file)
            if need_header:
                writer.writerow(["subject", "minutes"])
            writer.writerow([subject, minutes])
        totals = {}
        with path.open(newline="", encoding="utf-8") as file:
            for row in csv.DictReader(file):
                key = row["subject"].strip()
                totals[key] = totals.get(key, 0) + int(row["minutes"])
        for key in sorted(totals):
            print(f"{key}: {totals[key]} minutes")
