#!/usr/bin/env python3
"""Flatten nested order JSON (from the Barg Sabz mock API) into CSV rows — lesson AUT-201-L02.

One row per order item, because a spreadsheet cell cannot hold a list.
Standard library only. Input data is synthetic.

    python flatten_orders.py orders-page-1.json > orders.csv
"""
import csv
import json
import sys


def main(path):
    with open(path, encoding="utf-8") as f:
        doc = json.load(f)
    orders = doc.get("data")
    if not isinstance(orders, list):
        sys.exit("expected an object with a 'data' array")
    w = csv.writer(sys.stdout)
    w.writerow(["order_id", "status", "carrier", "item_title", "item_qty", "order_total"])
    for o in orders:
        items = o.get("items") or []
        if not isinstance(items, list):
            print(f"warning: {o.get('id')}: items is not a list, skipped", file=sys.stderr)
            continue
        if not items:  # keep orders without items visible instead of silently dropping them
            w.writerow([o.get("id"), o.get("status"), o.get("carrier") or "", "", "", o.get("total")])
        for it in items:
            w.writerow([o.get("id"), o.get("status"), o.get("carrier") or "", it.get("title"), it.get("qty"), o.get("total")])


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: python flatten_orders.py FILE.json")
    main(sys.argv[1])
