"""Lesson 2: comprehensions, generators, zip/enumerate and sorting with keys."""
import csv
from pathlib import Path
HERE = Path(__file__).resolve().parent
rows = list(csv.DictReader(open(HERE / "sales.csv", encoding="utf-8")))

pending = [r["invoice"] for r in rows if r["status"] == "Pending"]
print("Pending invoices:", len(pending), "first 3:", pending[:3])
by_rep = {rep: sum(1 for r in rows if r["rep"] == rep) for rep in sorted({r["rep"] for r in rows})}
print("Invoices per rep:", by_rep)
qty_total = sum(int(r["qty"]) for r in rows if r["qty"])          # generator: no list built in memory
print("Total quantity:", qty_total)
top = sorted(by_rep.items(), key=lambda kv: kv[1], reverse=True)[:2]
print("Top 2 reps:", top)
for i, (rep, n) in enumerate(top, start=1):
    print(f"  {i}. {rep:<7} {n:>3} invoices")
months = sorted({r["date"][:7] for r in rows if r["date"][4] == "-"})
print("Months:", months)
