import json
import csv

INPUT_FILE = "orders.json"
OUTPUT_FILE = "orders_separated.csv"

def main():
    # Load JSON array
    with open(INPUT_FILE, "r", encoding="utf-8") as f:
        data = json.load(f)

    # Ensure it's a list
    if not isinstance(data, list):
        raise ValueError("JSON file must contain a top-level array of objects.")

    # Convert nested fields to JSON strings
    for item in data:
        if "Customers" in item:
            item["Customers"] = json.dumps(item["Customers"], ensure_ascii=False)
        if "ProductsSold" in item:
            item["ProductsSold"] = json.dumps(item["ProductsSold"], ensure_ascii=False)

    # Collect all possible keys to ensure full CSV header
    all_keys = set()
    for item in data:
        all_keys.update(item.keys())
    fieldnames = list(all_keys)

    # Write CSV
    with open(OUTPUT_FILE, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(data)

    print(f"Saved {len(data)} rows to {OUTPUT_FILE}")

if __name__ == "__main__":
    main()
