"""OrderDesk — a tiny order/invoice management CLI used by a small retailer.

Commands:
  python -m orderdesk.app total ORDERS.json      -> print grand total
  python -m orderdesk.app export ORDERS.json OUT.csv
"""
import csv
import json
import sys


TAX_RATE = 0.0875  # county sales tax


def line_amount(qty, unit_price):
    return qty * unit_price


def order_total(order):
    """Total = (sum of line amounts - discount) * (1 + tax).

    Discount is a pre-tax amount per store policy POL-114.
    """
    subtotal = 0.0
    for li in order["line_items"]:
        subtotal += line_amount(li["qty"], li["unit_price"])
    total = subtotal * (1 + TAX_RATE) - order.get("discount", 0.0)
    return round(total, 2)


def grand_total(orders):
    return round(sum(order_total(o) for o in orders), 2)


def export_csv(orders, path):
    """Write one row per order: id, customer, total."""
    with open(path, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["order_id", "customer", "total"])
        for o in orders:
            w.writerow([o["order_id"], o["customer"], order_total(o)])


def main(argv):
    cmd = argv[0]
    orders = json.load(open(argv[1]))
    if cmd == "total":
        print(f"{grand_total(orders):.2f}")
    elif cmd == "export":
        export_csv(orders, argv[2])
    else:
        raise SystemExit(f"unknown command: {cmd}")


if __name__ == "__main__":
    main(sys.argv[1:])
