"""A single-writer study ledger for the original Omega M03 practice lab.""" import argparse import json import sys import tempfile from datetime import date from pathlib import Path def make_entry(title, day, minutes): """Validate three values and return a fresh record without doing any I/O.""" if not isinstance(title, str) or not title.strip(): raise ValueError("Title must contain some text.") title = title.strip() if not title.isprintable(): raise ValueError("Title must fit on one line and contain printable text.") try: parsed_day = date.fromisoformat(day) except (TypeError, ValueError): raise ValueError("Date must be a real date in YYYY-MM-DD format.") from None if parsed_day.isoformat() != day: raise ValueError("Date must be a real date in YYYY-MM-DD format.") if type(minutes) is not int or minutes < 0: raise ValueError("Duration must be a nonnegative whole number of minutes.") return {"title": title, "date": day, "minutes": minutes} def total_minutes(entries): """Compute the total for records that already passed validation.""" total = 0 for entry in entries: total += entry["minutes"] return total def load_entries(path): try: raw = path.read_text(encoding="utf-8") except FileNotFoundError: return [] except UnicodeDecodeError: raise ValueError("Ledger is not readable as UTF-8.") from None try: records = json.loads(raw) except json.JSONDecodeError as error: raise ValueError(f"Ledger contains invalid JSON at line {error.lineno}.") from None if not isinstance(records, list): raise ValueError("Ledger must contain a JSON list of study records.") entries = [] for position, record in enumerate(records, start=1): if not isinstance(record, dict) or set(record) != {"title", "date", "minutes"}: raise ValueError(f"Record {position} needs title, date and minutes fields.") try: entries.append(make_entry(record["title"], record["date"], record["minutes"])) except ValueError as error: raise ValueError(f"Record {position} is invalid. {error}") from None return entries def save_entries(path, entries): # Finish the write beside the destination before replacing its existing bytes. with tempfile.TemporaryDirectory(prefix=".ledger-", dir=path.parent) as directory: staged = Path(directory) / "ledger.json" staged.write_text(json.dumps(entries, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") staged.replace(path) def print_entries(entries): if not entries: print("No study entries yet.") for entry in entries: print(f"{entry['date']} | {entry['title']} | {entry['minutes']} min") print(f"Total: {total_minutes(entries)} min") def main(argv=None): parser = argparse.ArgumentParser(description="Add and list study records in a local JSON file.") parser.add_argument("--file", required=True, type=Path, help="Path to your practice ledger") commands = parser.add_subparsers(dest="command", required=True) commands.add_parser("list", help="Show entries and their total minutes") add = commands.add_parser("add", help="Record a study session") add.add_argument("title") add.add_argument("date", help="YYYY-MM-DD") add.add_argument("minutes", type=int) args = parser.parse_args(argv) try: if args.command == "add": entry = make_entry(args.title, args.date, args.minutes) entries = load_entries(args.file) entries.append(entry) save_entries(args.file, entries) print(f"Added: {entry['title']} ({entry['minutes']} min)") else: print_entries(load_entries(args.file)) except (ValueError, OSError) as error: print(f"Error: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())